Skip to content

Instantly share code, notes, and snippets.

@Maddocent
Forked from mmparker/calc_age.r
Created December 13, 2017 14:41
Show Gist options
  • Save Maddocent/4a008ae9af274b9c00206abeba01b793 to your computer and use it in GitHub Desktop.
Save Maddocent/4a008ae9af274b9c00206abeba01b793 to your computer and use it in GitHub Desktop.
Calculate years of age at a given date
# Calculate age at a given reference date
# Create an interval between the date of birth and the enrollment date;
# intervals are specific to the two dates. Periods give the actual length
# of time between those dates, so convert to period and extract the year.
calc_age <- function(birthDate, refDate = Sys.Date()) {
require(lubridate)
period <- as.period(new_interval(birthDate, refDate),
unit = "year")
period$year
}
# Examples
calc_age("1990-06-30") # As long as the date is %Y-%m-%d formatted, it can be a character
calc_age("1990-06-30", "2003-07-12") # Calculate age at any date
# Works for multiple reference dates, too
calc_age("1990-06-30", seq(from = as.Date("2003-01-01"), to = as.Date("2012-01-01"), by = "year"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment