1

I'm trying to account for infinite dates in PostgreSQL in a way that corresponds with the infinite date values described in this question. However, I can't get the code to work quite right.

df <- data.frame(dates = c("2012-08-06", "2014-05-05", 'infinity', '-infinity',as.character(Sys.Date())))

convertime <- function(x){
  time <- ifelse(
            x == 'infinity', 
              as.POSIXct(Inf, origin="1970-01-01"),
          ifelse(
            x == '-infinity', 
              as.POSIXct(-Inf, origin="1970-01-01"),
              as.POSIXct(x)
              )
          )
  return(time)
}
df$time <- convertime(df$dates)

This gives the following error:

Error in as.POSIXlt.character(as.character(x), ...) : 
character string is not in a standard unambiguous format

Any ideas?

TuringMachin
  • 391
  • 1
  • 4
  • 10

1 Answers1

1

ifelse constructs each of its possible values, and it bugs out on as.POSIXct("infinity").

Instead, try

converttime <- function(x,o="1970-01-01",posinf="infinity",neginf="-infinity"){
  xc <- x
  xc[x%in%c(posinf,neginf)] <- NA

  d            <- as.POSIXct(xc,   origin=o)
  d[x==posinf] <- as.POSIXct(Inf,  origin=o)
  d[x==neginf] <- as.POSIXct(-Inf, origin=o)

  d
}

d <- converttime(df$dates)
d[3] > d[4] # TRUE
Frank
  • 66,179
  • 8
  • 96
  • 180