Skip to content

Instantly share code, notes, and snippets.

@jalapic
Created February 6, 2016 18:10
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 jalapic/82beb6d2a3899db36219 to your computer and use it in GitHub Desktop.
Save jalapic/82beb6d2a3899db36219 to your computer and use it in GitHub Desktop.
calculate ages in r
# Calculate ages using lubridate
#option 1
library(lubridate)
library(dplyr)
today() #get today's date
today() - as.Date("1992-05-23") #calculate difference in days between two dates
as.period(today() - as.Date("1992-05-23"), units=c("year")) #convert to years
as.period(today() - as.Date("1992-05-23"), units=c("year")) %>% .$year #extract year
# option 2 - much better...
# This is an excellent customized function written by this person:
# http://stackoverflow.com/questions/14454476/get-the-difference-between-dates-in-terms-of-weeks-months-quarters-and-years
age <- function(dob, age.day = today(), units = "years", floor = TRUE) {
calc.age = new_interval(dob, age.day) / duration(num = 1, units = units)
if (floor) return(as.integer(floor(calc.age)))
return(calc.age)
}
age(as.Date('1977-03-28')) #calculates age of anyone
@jalapic
Copy link
Author

jalapic commented Feb 6, 2016

I think option2 might be a bit behind on birthdays .... but option1 seems accurate always.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment