-
-
Save smach/9421294 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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