Last active
August 13, 2021 18:58
-
-
Save mmparker/7254445 to your computer and use it in GitHub Desktop.
Calculate years of age at a given date
This file contains 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
# 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(), unit = "year") { | |
require(lubridate) | |
if(grepl(x = unit, pattern = "year")) { | |
as.period(interval(birthDate, refDate), unit = 'year')$year | |
} else if(grepl(x = unit, pattern = "month")) { | |
as.period(interval(birthDate, refDate), unit = 'month')$month | |
} else if(grepl(x = unit, pattern = "week")) { | |
floor(as.period(interval(birthDate, refDate), unit = 'day')$day / 7) | |
} else if(grepl(x = unit, pattern = "day")) { | |
as.period(interval(birthDate, refDate), unit = 'day')$day | |
} else { | |
print("Argument 'unit' must be one of 'year', 'month', 'week', or 'day'") | |
NA | |
} | |
} | |
# 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", unit = "months") # Other units available | |
calc_age("1990-06-30", "2003-07-12") # Calculate age at any date | |
# Works for babies: | |
calc_age("1990-06-30", "1990-12-12", unit = "month") | |
calc_age("1990-06-30", "1990-12-12", unit = "week") | |
# Works for multiple reference dates, too | |
calc_age(birthDate = "1990-06-30", | |
refDate = seq(from = as.Date("2003-01-01"), to = as.Date("2012-01-01"), by = "year") | |
) |
Thanks! Should exist a built in function to make this calculation
Very surprised to see these comments - guess I haven't been paying attention to Github for a few years!
I've updated the function to allow results in years, months, weeks, or days - which resolves @jenrichmond's question about 2.5 years too late.
Thanks to @ibelieveai for pointing out that new_interval was deprecated!
Thank you!!!! Had found Jen richmonds old post, continued looking, got here and just sorted out my dates in months column with minimal pain. Much appreicated!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks so much for this, I too have spent way to much time trying to work this out. I work with infants and was wondering how i might adapt this code to give age in months, or age in weeks. It seems that it is not as simple as just changing the unit. Any tips for this R newbie would be much appreciated!