Consider the following example:
structure(NA_real_, class = "Date")
## [1] NA
structure(Inf, class = "Date")
## [1] NA
is.na(structure(NA_real_, class = "Date"))
## [1] TRUE
is.na(structure(Inf, class = "Date"))
## [1] FALSE
Both are printing as NA. Is this the expected behavior or is this an error? It is very annoying to see NA for something that won't return TRUE for is.na().
This is expected behavior. What is printed is not what the object is. To be printed, the object needs to be converted to character. as.character.Date calls format.Date, which calls format.POSIXlt. The Value section of ?format.POSIXlt (or ?strptime) says:
The
formatmethods andstrftimereturn character vectors representing the time.NAtimes are returned asNA_character_.
So that's why NA is printed, because printing structure(NA_real_, class = "Date") returns NA_character_. For example:
R> is.na(format(structure(Inf, class = "Date")))
[1] TRUE
R> is.na(format(structure(NaN, class = "Date")))
[1] TRUE
If you somehow encounter these wonky dates in your code, I recommend you test for them using is.finite instead of is.na.
R> is.finite(structure(Inf, class = "Date"))
[1] FALSE
R> is.finite(structure(NaN, class = "Date"))
[1] FALSE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With