R-date temporary variable loses format after ifelse

I have a variable in the correct POSIXct format, converted using ymd_hms (DateTime) {lubridate}. However, after the conversion, the variable loses its POSIXct format:

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

I am trying to convert the variable again to POSIXct with lubridate, but it seems like NA doesn’t like it, and besides, now the DateTime variable has num format, which lubridate does not recognize as date and time format (e.g. 1377419400).

Please any help to make the necessary conversion to convert to NA DateTime when id == r1_1 and r1_2 ??

thanks

+4
source share
2 answers

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 also good. There is only the general logic for installing is.na, which does not make much sense, but this is not a problem if you make sure that everything is not so complicated.)

ifelse does some implicit conversion, so I don’t think that the date class will ever be saved using ifelse .

+2
source

The idiomatic way to set NA values ​​is to use is.na<- , most classes (including dates) will be handled accordingly

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

Gotta 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" 
+2
source

All Articles