An alternative title to this question is:
When is an NA date not an NA?
Answer: when it is infinity formatted as a date.
Converting infinity to a date results in NA being displayed, but it is not!
> BadDates <- as.Date(c(NA,Inf,-Inf))
> BadDates
[1] NA NA NA
> is.na(BadDates)
[1] TRUE FALSE FALSE
This causes confusion when trying to catch errors. A work-around is to test for infinity and NA
> is.na(BadDates) & is.infinite(BadDates)
[1] FALSE FALSE FALSE
Is there a better way to manage this quirk of the Date class?
CodePudding user response:
is.finite(as.Date(NA))
and is.infinite(as.Date(NA))
are both FALSE so is.finite
will be FALSE for all the bad dates but TRUE for a good date.
BadDates <- as.Date(c(NA,Inf,-Inf))
is.finite(BadDates)
## [1] FALSE FALSE FALSE
GoodDate <- Sys.Date()
is.finite(GoodDate)
## [1] TRUE
It works the same without dates so it is not specific to Date class.
x <- c(NA, Inf, -Inf)
is.finite(x)
## [1] FALSE FALSE FALSE
is.finite(3)
## [1] TRUE