Calculate ages in R

前端 未结 8 1854
北荒
北荒 2020-11-27 16:39

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.

8条回答
  •  星月不相逢
    2020-11-27 17:24

    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.

提交回复
热议问题