4

I have a variable in the proper POSIXct format, converted with ymd_hms(DateTime) {lubridate}. However, after a transformation the variable loses its POSIXct format:

daily$DateTime<- ifelse(daily$ID %in% "r1_1"|daily$ID %in% "r1_2", 
                   NA,daily$DateTime)

I try to convert the variable again to POSIXct with lubridate, but it seems it does´t like the NAs, and, in addition, now the variable DateTime has a num format that lubridate does´t recognise as a date and time format (e.g. 1377419400).

Please, any help to make the required transformation to convert to NA the DateTime when ID== r1_1 and r1_2??

Thanks

fede_luppi
  • 1,063
  • 4
  • 17
  • 29
  • https://stackoverflow.com/questions/6668963/how-to-prevent-ifelse-from-turning-date-objects-into-numeric-objects – M-- May 14 '19 at 18:39

2 Answers2

2

The idiomatic way to set NA values is to use is.na<-, most classes (including Dates) will be dealt with appropriately

 is.na(daily$DateTime) <- daily$ID %in% c('r1_1', 'r1_2')

Should do the trick.

Using the example from ?as.POSIXct

  ## SPSS dates (R-help 2006-02-16)
z <- c(10485849600, 10477641600, 10561104000, 10562745600)
zz <- as.POSIXct(z, origin = "1582-10-14", tz = "GMT")

is.na(zz) <- c(FALSE, TRUE, FALSE, FALSE)
zz
# [1] "1915-01-26 GMT" NA               "1917-06-15 GMT" "1917-07-04 GMT"
mnel
  • 113,303
  • 27
  • 265
  • 254
  • 3
    John Chambers says, however, that the "idiomatic" way of setting NAs with is.na is a bad idea. Think about what happens when you set some NA elements in a vector to being not NA's? The result is weird - you set is.na(x)<-FALSE but is.na(x) is still TRUE. So I'd say the only sensible way to set something to NA is using x<-NA rather than is.na(x) <- TRUE. And the former is shorter. – lebatsnok Sep 26 '13 at 10:05
2

The following should work:

daily <- data.frame(DateTime = seq(Sys.time(), length.out=10, by=1000), ID=rep(1:2,5))
daily$DateTime[daily$ID%in%2]<-NA

(Although the solution with is.na<- is fine too. There is just the general logic of setting is.na that doesn't make much sense - but that's no problem as long as you make sure things don't get too complicated.)

ifelse does some implicit conversions so I don't think it would ever be possible to have a date class preserved using ifelse.

lebatsnok
  • 6,329
  • 2
  • 21
  • 22