Skip to content

Instantly share code, notes, and snippets.

@mmparker mmparker/calc_age.r

Last active Jun 27, 2019
Embed
What would you like to do?
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"))
@smach

This comment has been minimized.

Copy link

smach commented Mar 7, 2014

Thanks for this!

@mattparker-wf

This comment has been minimized.

Copy link

mattparker-wf commented Feb 19, 2015

Note: this currently isn't working with the CRAN release of lubridate (1.3.3), but does work with the development version of the package. Just use library(devtools); install_github("lubridate") to install that version.

@ibelieveai

This comment has been minimized.

Copy link

ibelieveai commented Jul 22, 2016

Thank you ! It's working. As new_interval is deprecated we need to use interval instead

@YiL17

This comment has been minimized.

Copy link

YiL17 commented Jul 12, 2017

Amazing! Thanks a lot :) 👍

@rdsilva

This comment has been minimized.

Copy link

rdsilva commented Mar 1, 2018

Awesome!
Worked perfect with me, thanks!

@KathParamedic

This comment has been minimized.

Copy link

KathParamedic commented Apr 15, 2018

Fantastic.. Have spent too many hours trying to work out how to do this, before I stumbled across this..

@jenrichmond

This comment has been minimized.

Copy link

jenrichmond commented Aug 3, 2018

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.