Calculate ages in R

Viewed 41116

I have two data frames in R. One frame has a persons year of birth:

YEAR
/1931
/1924

and then another column shows a more recent time.

RECENT
09/08/2005
11/08/2005

What I want to do is subtract the years so that I can calculate their age in number of years, however I am not sure how to approach this. Any help please?

8 Answers

Really solid way that also supports vectors using the lubridate package:

age <- function(date.birth, date.ref = Sys.Date()) {
  if (length(date.birth) > 1 & length(date.ref) == 1) {
    date.ref <- rep(date.ref, length(date.birth))
  }

  date.birth.monthdays <- paste0(month(date.birth), day(date.birth)) %>% as.integer()
  date.ref.monthdays <- paste0(month(date.ref), day(date.ref)) %>% as.integer()

  age.calc <- 0

  for (i in 1:length(date.birth)) {
    if (date.birth.monthdays[i] <= date.ref.monthdays[i]) {
      # didn't had birthday
      age.calc[i] <- year(date.ref[i]) - year(date.birth[i])
    } else {
      age.calc[i] <- year(date.ref[i]) - year(date.birth[i]) - 1
    }
  }
  age.calc
}

This also accounts for leap years. I just check if someone has had a birthday already.

Related