Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R `Inf` when it has class `Date` is printing `NA`

Tags:

r

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().

like image 683
stanekam Avatar asked Dec 18 '14 19:12

stanekam


Video Answer


1 Answers

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 format methods and strftime return character vectors representing the time. NA times are returned as NA_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
like image 108
Joshua Ulrich Avatar answered Sep 22 '22 18:09

Joshua Ulrich