本文介绍了R ifelse 避免更改日期格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为两个日期制作 ifesle.我有两列 - DateIn 和 DateOut.我需要添加第三个变量,如果有日期值,它将显示DateOut",如果有,则显示 DateIn:
I am trying to make ifesle for two dates. I have two columns- DateIn and DateOut. I need to add 3rd variable, which would show "DateOut" if there is date value, or DateIn if there is :
DateIn DateOut Travel date
2010-11-24 <NA> 2010-11-24
2011-12-21 2012-01-21 2012-01-21
2010-10-25 2010-11-25 2010-11-25
2014-01-14 <NA> 2014-01-14
我试图这样做
TravelDate <- ifelse(is.na(DateIn), DateOut, DateIn)
但我得到的结果是:
DateIn DateOut Travel date
2010-11-24 <NA> 15018
2011-12-21 2012-01-21 15151
2010-10-25 2010-11-25 14972
2014-01-14 <NA> 14972
旅行日期被归类为合乎逻辑"有没有办法在没有 R 将日期转换为数字的情况下实现结果?
Travel date is classified as "logical"Is there a ways how to achieve the rusult withou R transforming date to number?
非常感谢!
推荐答案
如果 dat
是数据集.我假设它是 is.na(DateOut)
来自 Travel date
列
If dat
is the dataset. I assume it is is.na(DateOut)
from the Travel date
column
as.Date(with(dat, ifelse(is.na(DateOut), DateIn, DateOut)),origin="1970-01-01")
#[1] "2010-11-24" "2012-01-21" "2010-11-25" "2014-01-14"
或者你可以这样做:
dat$Travel.date <- dat$DateOut
dat$Travel.date[is.na(dat$Travel.date)] <- dat$DateIn[is.na(dat$Travel.date)]
dat
# DateIn DateOut Travel.date
#1 2010-11-24 <NA> 2010-11-24
#2 2011-12-21 2012-01-21 2012-01-21
#3 2010-10-25 2010-11-25 2010-11-25
#4 2014-01-14 <NA> 2014-01-14
这篇关于R ifelse 避免更改日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!