1
d <-c("1948/05/28","1952/03/27","1994/12/09")
as.Date(d)
[1] "1948-05-28" "1952-03-27" "1994-12-09"
as.Date("2014-03-20")
[1] "2014-03-20"
as.Date("2014-03-20")-as.Date(d)
Time differences in days
[1] 24037 22638  7041
(as.Date("2014-03-20")-as.Date(d))/365
Time differences in days
[1] 65.85479 62.02192 19.29041

I use (as.Date("2014-03-20")-as.Date(d))/365 to get the years between them ,is there more formal way to do that?

zx8754
  • 52,746
  • 12
  • 114
  • 209
showkey
  • 482
  • 42
  • 140
  • 295

3 Answers3

0

lubridate::as.interval() addresses exactly that.

smci
  • 32,567
  • 20
  • 113
  • 146
0

Try this to ensure that it picks days as the unit. Also 365.25 is slightly better than 365 due to leap years:

as.numeric(difftime(as.Date("2014-03-20"), as.Date(d), unit = "days")) / 365.25
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
0

This is a more efficient modification of G. Grothendieck's answer:

(as.integer(as.Date("2014-03-20")) - as.integer(as.Date(d))) / 365.25
DMillan
  • 119
  • 6