Search code examples
rdateinfinity

Why do dates at infinity look like NAs but act like dates?


I was trying to figure out the best way to deal with Postgresql's ability to represent Infinity and -Infinity in their timestamps when using RPostgreSQL to bring data over into R. Along the way I found some strange behavior when trying to represent infinite dates in R.

I can attempt to create a date at negative and positive infinity in the following manner:

❥ as.Date(-1/0, origin="1970-01-01")
[1] NA
❥ as.Date(1/0, origin="1970-01-01")
[1] NA

They both appear to be NAs. However when comparing them, there seems to be an understanding that one is less than the other.

❥ as.Date(-1/0, origin="1970-01-01") < as.Date(1/0, origin="1970-01-01")
[1] TRUE
❥ as.Date(-1/0, origin="1970-01-01") > as.Date(1/0, origin="1970-01-01")
[1] FALSE
❥ as.Date(1/0, origin="1970-01-01") > as.Date("1970-01-01")
[1] TRUE
❥ as.Date(1/0, origin="1970-01-01") < as.Date("1970-01-01")
[1] FALSE

How does R know the difference, if they both convert to NA?


Solution

  • They don't convert to NA, that's just how they're printed.

    R> d <- as.Date(-Inf, origin="1970-01-01")
    R> is.na(d)
    # [1] FALSE
    R> is.infinite(d)
    # [1] TRUE
    

    If you want them to print differently, you can override the print.Date method and add special cases for +/- infinity.