【问题标题】:R infinity dates mixed with textR无限日期与文本混合
【发布时间】:2015-07-19 17:21:45
【问题描述】:

我试图以一种与this question 中描述的无限日期值相对应的方式来解释 PostgreSQL 中的无限日期。但是,我无法让代码正常工作。

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)

这会产生以下错误:

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

有什么想法吗?

【问题讨论】:

    标签: r date infinity rpostgresql


    【解决方案1】:

    ifelse 构造其每个可能的值,并在as.POSIXct("infinity") 上出错。

    相反,试试

    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
    

    【讨论】:

      猜你喜欢
      • 2016-11-09
      • 1970-01-01
      • 1970-01-01
      • 2016-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-21
      • 1970-01-01
      相关资源
      最近更新 更多