问题
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
回答1:
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
.
回答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"
来源:https://stackoverflow.com/questions/19019820/r-date-time-variable-loses-format-after-ifelse