R ifelse avoiding change in date format [duplicate]

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!


Solution 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

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