0

Suppose I'm converting the below date from character to simple date format in R.

character_date <- "19-Jan-44"
date <- as.Date(strptime(x = as.character(character_date), format= "%d-%b-%y"))
> date
[1] "2044-01-19"

R assumes it's 2044 instead of 1944 (which is the desired), how do I tell R which year it actually was?

Thanks a lot!

Lin
  • 93
  • 8
  • You need to provide the context as to whether it can be 1944 or 2044 – akrun Jan 04 '17 at 09:02
  • 1
    Then how do you show a date with the year 2044 or 1844? or it has to be assumed that every date is going to belong to 19th century? – Ronak Shah Jan 04 '17 at 09:02
  • If you always assumr the 20th century, I guess you could just embed it into your string, something like `as.Date(gsub("(.*)-(.*)", "\\1-19\\2", character_date), format= "%d-%b-%Y")` and please please don't use `strptime` when converting to `Date` class – David Arenburg Jan 04 '17 at 09:08

2 Answers2

1

We can create a function to do this

library(lubridate)
f1 <- function(x, year=1970){
   x <- dmy(x)
   m <- year(x) %% 100
   year(x) <- ifelse(m > year %% 100, 2000+m, 1900+m)
  x
}

f1(character_date)
#[1] "1944-01-19"

If this always have 19 as prefix for year

dmy(sub("-(\\d+)", "-19\\1", character_date))
#[1] "1944-01-19"
akrun
  • 874,273
  • 37
  • 540
  • 662
0

You can just append a "-19" to the string and do format = "%d-%b-y-%C".

Hermann Döppes
  • 1,373
  • 1
  • 18
  • 26