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

后端 未结 1 486
栀梦
栀梦 2020-12-06 05:44

Consider the following example:

structure(NA_real_, class = \"Date\")
## [1] NA
structure(Inf, class = \"Date\")
## [1] NA
is.na(structure(NA_real_, class =          


        
相关标签:
1条回答
  • 2020-12-06 06:17

    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
    
    0 讨论(0)
提交回复
热议问题