我正在尝试为两个日期制作ifesle。我有两列 - DateIn和DateOut。我需要添加第三个变量,它将显示" DateOut"如果有日期值,或者如果有,则为DateIn:
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
旅行日期分类为&#34;逻辑&#34; 有没有办法如何通过R转换日期到数字来实现rusult?
非常感谢!
答案 0 :(得分:4)
如果dat
是数据集。我假设它是is.na(DateOut)
列
Travel date
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
答案 1 :(得分:1)
将DateOut
分配给Travel.date
,然后DateOut
NA
的组件使用DateIn
将replace
替换为DF2 <- transform(DF, Travel.date = DateOut)
isna <- is.na(DF2$DateOut)
transform(DF2, Travel.date = replace(Travel.date, isna, DateIn[isna]))
:
DF <- structure(list(DateIn = structure(c(14937, 15329, 14907, 16084
), class = "Date"), DateOut = structure(c(NA, 15360, 14938, NA
), class = "Date"), Travel.date = structure(c(NA, 15360, 14938,
NA), class = "Date")), .Names = c("DateIn", "DateOut", "Travel.date"
), row.names = c(NA, -4L), class = "data.frame")
我们假设了这个测试数据:
{{1}}
答案 2 :(得分:0)
让我们假设这是一个名为&#39; dat&#39;的数据帧。我猜你正在使用&#39; attach&#39;我会建议你放弃这种被误导的方法,因为它会使你更频繁地绊倒你所节省的打字时间会被它造成的混乱所浪费。相反,修改您正在使用的代码非常容易:
dat$TravelDate <- as.Date( with(dat,
ifelse(is.na(DateIn), DateOut, DateIn)), origin="1970-01-01")
dat
DateIn DateOut Travel_date TravelDate
1 2010-11-24 <NA> 2010-11-24 2010-11-24
2 2011-12-21 2012-01-21 2012-01-21 2011-12-21
3 2010-10-25 2010-11-25 2010-11-25 2010-10-25
4 2014-01-14 <NA> 2014-01-14 2014-01-14
数据测试用例。请注意,列名称已删除空格:
dat<- read.table(textConnection("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"), header=TRUE, colClasses="Date")