1

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!

user1357015
  • 11,168
  • 22
  • 66
  • 111
  • http://stackoverflow.com/questions/12323693/is-there-a-more-elegant-way-to-convert-two-digit-years-to-four-digit-years-with – akrun Dec 31 '14 at 08:37
  • 1
    try `format(as.Date("65-05-14", "%y-%m-%d"), "19%y-%m-%d")` – KFB Dec 31 '14 at 08:39
  • @KFB, I'm presuming this came from http://stackoverflow.com/q/9508747/1270695.... Should this be closed as a duplicate of one of these questions? – A5C1D2H2I1M1N2O1R2T1 Dec 31 '14 at 08:41
  • @KFB: hm -- would that only work for the 90's? Say instead I head 114 (corresponding to 2014). I think yours might crash. – user1357015 Dec 31 '14 at 08:42
  • 1
    Try maybe using `POSIXlt` class, something like `Date <- as.POSIXlt(as.Date("65-05-14", "%y-%m-%d")) ; Date$year <- Date$year - 100L`. Should also work on a whole vector. – David Arenburg Dec 31 '14 at 08:43
  • 1
    @user1357015, Seems the link provided by Ananda has the answer to your question. Have a look. – KFB Dec 31 '14 at 08:43

1 Answers1

2

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"
David Arenburg
  • 91,361
  • 17
  • 137
  • 196