Created
February 6, 2016 18:10
calculate ages in r
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 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think option2 might be a bit behind on birthdays .... but option1 seems accurate always.