Get date difference in years (floating point)

Solution 1:

Yes, of course, use difftime() with an as numeric:

R> as.numeric(difftime(as.Date("2003-04-05"), as.Date("2001-01-01"), 
+                      unit="weeks"))/52.25
[1] 2.2529
R> 

Note that we do have to switch to weeks scaled by 52.25 as there is a bit of ambiguity there in terms of counting years---a February 29 comes around every 4 years but not every 100th etc.

So you have to define that. difftime() handles all time units up to weeks. Months cannot be done for the same reason of the non-constant 'numerator'.

Solution 2:

The lubridate package contains a built-in function, time_length, which can help perform this task.

time_length(difftime(as.Date("2003-04-05"), as.Date("2001-01-01")), "years")
[1] 2.257534

time_length(difftime(as.Date("2017-03-01"), as.Date("2012-03-01")),"years")
[1] 5.00274

Documentation for the lubridate package can be found here.

Solution 3:

Inspired by Bryan F, time_length() would work better if using interval object

time_length(interval(as.Date("2003-04-05"), as.Date("2001-01-01")), "years")
[1] -2.257534
time_length(difftime(as.Date("2017-03-01"), as.Date("2012-03-01")),"years")
[1] 5.00274
time_length(interval(as.Date("2017-03-01"), as.Date("2012-03-01")),"years")
[1] -5

You can see if you use interval() to get the time difference and then pass it to time_length(), time_length() would take into account the fact that not all months and years have the same number of days, e.g., the leap year.