Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add correct century to dates with year provided as "Year without century", %y

Tags:

r

I have an file with birthdays in %d%b%y format. Some eg.

# "01DEC71" "01AUG54" "01APR81" "01MAY81" "01SEP83" "01FEB59"

I tried to reformat the date as

o108$fmtbirth <- format(as.Date(o108$birth, "%d%b%y"), "%Y/%m/%d")

and this is the result

# "1971/12/01" "2054/08/01" "1981/04/01" "1981/05/01" "1983/09/01" "2059/02/01"

These are birthdays and I see 2054. From this page I see that year values between 00 and 68 are coded as 20 for century. Is there a way to toggle this, in my case I want only 00 to 12 to be coded as 20.

like image 864
user3897 Avatar asked Feb 29 '12 22:02

user3897


2 Answers

1) chron. chron uses 30 by default so this will convert them converting first to Date (since chron can't read those sorts of dates) reformatting to character with two digit years into a format that chron can understand and finally back to Date.

library(chron)
xx <- c("01AUG11", "01AUG12", "01AUG13") # sample data
as.Date(chron(format(as.Date(xx, "%d%b%y"), "%m/%d/%y")))

That gives a cutoff of 30 but we can get a cutoff of 13 using chron's chron.year.expand option:

library(chron)
options(chron.year.expand = 
     function (y, cut.off = 12, century = c(1900, 2000), ...) {
        chron:::year.expand(y, cut.off = cut.off, century = century, ...)
     }
)

and then repeating the original conversion. For example assuming we had run this options statement already we would get the following with our xx :

> as.Date(chron(format(as.Date(xx, "%d%b%y"), "%m/%d/%y")))
[1] "2011-08-01" "2012-08-01" "1913-08-01"

2) Date only. Here is an alternative that does not use chron. You might want to replace "2012-12-31" with Sys.Date() if the idea is that otherwise future dates are really to be set 100 years back:

d <- as.Date(xx, "%d%b%y")
as.Date(ifelse(d > "2012-12-31", format(d, "19%y-%m-%d"), format(d)))

EDIT: added Date only solution.

like image 121
G. Grothendieck Avatar answered Nov 20 '22 04:11

G. Grothendieck


See response from related thread:

format(as.Date("65-05-14", "%y-%m-%d"), "19%y-%m-%d")
like image 29
Chad Johnson Avatar answered Nov 20 '22 04:11

Chad Johnson