简体   繁体   中英

R incorrect value of date function

I'm trying to use as.Date in R.

I'm using the command:

as.Date("65-05-14", "%y-%m-%d")

I get:

"2065-05-14"

Is there any way to get it show 1965 instead? Or do I need to recode everything into long format -- eg add 1900 as a numeric?

Thanks!

I didn't see this simple solution in the linked questions, so I'm adding it here too.

In base R you can simply use as.POSIXlt class which provides year attribute. You can then simply reduce 100 years.

Lets say this is your dates vector

(Date <- c("65-05-14", "15-05-14", "25-05-14", "34-05-14"))
## [1] "65-05-14" "15-05-14" "25-05-14" "34-05-14"

You can simply do

Date <- as.POSIXlt(Date, format = "%y-%m-%d")
Date$year <- Date$year - 100L
Date # Alternatively, you could also do `as.Date(Date)`
## [1] "1965-05-14 IDT" "1915-05-14 IDT" "1925-05-14 IDT" "1934-05-14 IDT"

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