1

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?

Rainfall.NZ
  • 197
  • 1
  • 12
  • Strangely, if BadDates was specified as: `BadDates <- as.Date(c(NA,Inf,-Inf,"Rhubarb"),optional=TRUE)` then `is.na(BadDates)` returns `TRUE TRUE TRUE TRUE` – Rainfall.NZ Jan 14 '23 at 23:26

1 Answers1

1

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
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341