简体   繁体   中英

date variables in R

I have dates that are before 1969 stored as a character and want to change them to a date column.

This is the code I've tried

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")))

But I get the warning message:

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

With the output:

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

Can anyone tell me where I'm going wrong?

Reproducible example;

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

Expected outcome:

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

Your problem was that you used as.Date which represents ambiguous dates as post-1970 (see here ). Output of the vector you passed into chron using as.Date :

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

Correct way to do it was to not use as.Date to convert the date first but use chron with the format option directly:

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM