Calculate ages in R

前端 未结 8 1852
北荒
北荒 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:22

    I use a custom function, see code below, convenient to use in mutate and quite flexible (you'll need the lubridate package).

    Examples

    get_age("2000-01-01")
    # [1] 17
    get_age(lubridate::as_date("2000-01-01"))
    # [1] 17
    get_age("2000-01-01","2015-06-15")
    # [1] 15
    get_age("2000-01-01",dec = TRUE)
    # [1] 17.92175
    get_age(c("2000-01-01","2003-04-12"))
    # [1] 17 14
    get_age(c("2000-01-01","2003-04-12"),dec = TRUE)
    # [1] 17.92176 14.64231
    

    Function

    #' Get age
    #' 
    #' Returns age, decimal or not, from single value or vector of strings
    #' or dates, compared to a reference date defaulting to now. Note that
    #' default is NOT the rounded value of decimal age.
    #' @param from_date vector or single value of dates or characters
    #' @param to_date date when age is to be computed
    #' @param dec return decimal age or not
    #' @examples
    #' get_age("2000-01-01")
    #' get_age(lubridate::as_date("2000-01-01"))
    #' get_age("2000-01-01","2015-06-15")
    #' get_age("2000-01-01",dec = TRUE)
    #' get_age(c("2000-01-01","2003-04-12"))
    #' get_age(c("2000-01-01","2003-04-12"),dec = TRUE)
    get_age <- function(from_date,to_date = lubridate::now(),dec = FALSE){
      if(is.character(from_date)) from_date <- lubridate::as_date(from_date)
      if(is.character(to_date))   to_date   <- lubridate::as_date(to_date)
      if (dec) { age <- lubridate::interval(start = from_date, end = to_date)/(lubridate::days(365)+lubridate::hours(6))
      } else   { age <- lubridate::year(lubridate::as.period(lubridate::interval(start = from_date, end = to_date)))}
      age
    }
    

提交回复
热议问题