Reputation: 1600
I am trying to test if elements of a date vector are of length 0.
this works fine using base R, but returns POSIXct as numeric:
a<-numeric(0)
>ifelse(length(a)==1,a,as.POSIXct("2017-12-26 17:53:53 AEDT"))
[1] 1514271233
a solution to keep the class is to use dplyr or data.table, but they both return errors:
>dplyr::if_else(length(a)==1,a,as.POSIXct("2017-12-26 17:53:53 AEDT"))
Error: `true` must be length 1 (length of `condition`), not 0
Run `rlang::last_error()` to see where the error occurred.
>data.table::fifelse(length(a)==1,a,as.POSIXct("2017-12-26 17:53:53 AEDT"))
Error in data.table::fifelse(length(a) == 1, a, as.POSIXct("2017-12-26 17:53:53 AEDT")) :
'yes' has different class than 'no'. Please make sure that both arguments have the same class.
why is it different? I thought these functions would just ignore the TRUE
option when the logical test returns FALSE
. Is there a solution that doesn't involve converting back to POSIXct?
Upvotes: 1
Views: 208
Reputation: 24790
How about the good old fashioned way?
if(length(a)==1){a}else(as.POSIXct("2017-12-26 17:53:53 AEDT"))
[1] "2017-12-26 17:53:53 EST"
Upvotes: 1