R中的日期变量

date variables in R

我将 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

您的问题是您使用了 as.Date,它将不明确的日期表示为 post-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"