R ifelse avoiding change in date format [duplicate]

半腔热情 提交于 2019-11-28 02:05:46
akrun

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"

Or you can do:

 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

Assign DateOut to Travel.date and then for components of DateOut which are NA replace them with DateIn using replace:

DF2 <- transform(DF, Travel.date = DateOut)
isna <- is.na(DF2$DateOut)
transform(DF2, Travel.date = replace(Travel.date, isna, DateIn[isna]))

We have assumed this test data:

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")

Lets assume this is in a dataframe named 'dat'. I'm guessing your are using 'attach' and I would advise you to drop that misguided approach, since it will trip you up more often than not and the saved time in typing will be wasted by the confusion it creates. Instead it would be quite easy to modify the code the you are using:

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

Data test case. Note that the col name had the space removed:

 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")
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!