Skip to content

Instantly share code, notes, and snippets.

@smach
Forked from mmparker/calc_age.r
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smach/9421294 to your computer and use it in GitHub Desktop.
Save smach/9421294 to your computer and use it in GitHub Desktop.
# Useful lubridate function for date subtraction written by mmparker
# 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