Why do dates at infinity look like NAs but act like dates? [duplicate]
Asked Answered
E

1

18

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?

Eggbeater answered 8/5, 2015 at 16:42 Comment(1)
I am not an expert on R but my guess is that these are internally represented as special cases and you can easily compare them by always saying everything is after -Infinity (date) and everything is before Infinity (date). Most programming languages treat such values as special cases anyway (as objects anyway).Cenis
A
19

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.

Armour answered 8/5, 2015 at 17:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.