【问题标题】:date variables in RR中的日期变量
【发布时间】:2018-06-27 13:36:21
【问题描述】:

我将 1969 年之前的日期存储为一个字符,并希望将它们更改为日期列。

这是我尝试过的代码

options(chron.year.expand = 
          function (y, cut.off = 19, century = c(1900, 2000), ...) {
            chron:::year.expand(y, cut.off = cut.off, century = century, ...)
          }
)

test$construction_date2<-as.Date(chron(format(as.Date(test$construction_date,  "%d-%b-%y"),"%d/%m/%Y")))

但我收到警告消息:

Warning message:
In convert.dates(dates., format = fmt, origin. = origin.) :
  224 months out of range set to NA

输出:

construction_date     contruction_date2
23-MAR-59                  2059-03-23
05-JUN-95                  1995-06-05
30-MAY-87                  1987-05-30
15-JAN-18                  NA
01-FEB-68                  2068-02-01

谁能告诉我哪里出错了?

可重现的例子;

constuction_date<-c("23-MAR-59","05-JUN-95","30-MAY-87","15-JAN-18","01-FEB-68")

预期结果:

construction_date     contruction_date2
23-MAR-59                  1959-03-23
05-JUN-95                  1995-06-05
30-MAY-87                  1987-05-30
15-JAN-18                  2018-01-15
01-FEB-68                  1968-02-01

【问题讨论】:

  • 如果您可以为可重现的示例提供输入数据的子集和所需的输出,那么这里的人们会更容易为您提供帮助。谢谢:)
  • @mysteRious 我已经添加了这些,谢谢 :)
  • 看起来有人已经发布了lubridate 解决方案......这也是让我获得最大成功的包 :)
  • @mysteRious dmy 函数将返回 2059 而不是 195959 值。我删除了我的答案。

标签: r date datetime chron


【解决方案1】:

您的问题是您使用了 as.Date,它表示 1970 年后的模棱两可的日期(请参阅 here)。使用as.Date 传递给chron 的向量的输出:

> as.Date(construction_date,"%d-%b-%y")
[1] "2059-03-23" "1995-06-05" "1987-05-30" "2018-01-15" "2068-02-01"

正确的做法是先不要使用as.Date 转换日期,而是直接使用chronformat 选项:

options(chron.year.expand = 
          function (y, cut.off = 19, century = c(1900, 2000), ...) {
            chron:::year.expand(y, cut.off = cut.off, century = century, ...)
          }
)

> as.Date(chron(dates.=construction_date,format="day-month-year"))
[1] "1959-03-23" "1995-06-05" "1987-05-30" "2018-01-15" "1968-02-01"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-24
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多