问题
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
I tried to do that with
TravelDate <- ifelse(is.na(DateIn), DateOut, DateIn)
But the result I am gettin is:
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
Travel date is classified as "logical" Is there a ways how to achieve the rusult withou R transforming date to number?
Thanks a lot!
回答1:
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
回答2:
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")
回答3:
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")
来源:https://stackoverflow.com/questions/24983470/r-ifelse-avoiding-change-in-date-format