Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the difference between two two-digit years

Tags:

r

difference

Is there any easy way in R to calculate the difference between two columns of two-digit years (just years, no months/days as it's unnecessary here) in order to produce a column of ages?

I've fairly new to this and have been playing with 'if' statements and algebra without success.

The data looks like this, but larger:

dat <- data.frame(year1=c("98","99","00","01","02"),
                  year2=c("03","04","05","06","07"))
like image 641
mothballs Avatar asked May 21 '26 06:05

mothballs


1 Answers

You could use strptime() with the format %y:

dat <- data.frame(year1=c("98","99","00","01","02"),
    year2=c("03","04","05","06","07"),
    stringsAsFactors = F) # You might want to use this as a default!

dat$year1 <- strptime(dat$year1, format = "%y")
dat$year2 <- strptime(dat$year2, format = "%y")

as.vector(difftime(dat$year2,
    dat$year1,
    units = "days"))/365.242
4.999311 5.002163 4.999425 4.999425 4.999425
like image 55
tobiasegli_te Avatar answered May 23 '26 20:05

tobiasegli_te



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!