Reputation: 1
Mydata has a date with time.
Date:
2008-04-21 11:00:00
NA
NA
2008-04-20 11:00:00
str(Mydata)
said that Date is POSIXct. So I'm trying to create a new variable.
myData$Date2 <- ifelse(is.na(Mydata$OtherVariable), NA, Mydata$Date)).
I want to create a new variable that is NA if OtherVariable is NA, or exactly Mydata$Date if not. But Mydata$Date gave me a number like 1.24e+09, maybe does not recognise date POSIXct. I tried as.POSIXct(Mydata$Date) but doesn't work.
Upvotes: 0
Views: 133
Reputation: 389135
If you want to use ifelse
use dplyr::if_else
which is type-strict and will not change the time to numbers.
Mydata$Date2 <- dplyr::if_else(is.na(Mydata$OtherVariable),
as.POSIXct(NA, tz = 'UTC'), Mydata$Date)
Or another way without using ifelse
in base R would be :
Mydata$Date2 <- as.POSIXct(NA, tz = 'UTC')
inds <- !is.na(Mydata$OtherVariable)
Mydata$Date2[inds] <- Mydata$Date[inds]
Upvotes: 1