Floris Floris - 8 months ago 29
R Question

Count the number of years ago from a date

I have retrieved my birthday in the format 06/23/1993 from Facebook and I want to turn this birthday into my age.

This is the code I have so far:

install.packages("eeptools")
library(eeptools)

as.POSIXct(facebook$birthday, tz = "", format = "%m/%d/%Y", origin="1970-01-01")
as.Date(facebook$birthday, format = "%m/%d/%Y")

facebook$age <- floor(age_calc(facebook$birthday, units = "years"))


After the first 2 lines it returns this:

as.POSIXct(facebook$birthday, tz = "", format = "%m/%d/%Y", origin="1970-01-01")
#[1] "1993-06-23 CEST"
as.Date(facebook$birthday, format = "%m/%d/%Y")
#[1] "1993-06-23"


After the last line I get this error:


Error in age_calc(facebook$birthday, units = "years") :
Both dob and enddate must be Date class objects


Would be much appreciated if anyone could help me out :)

Resolved!
Edit: I just forgot to insert as.Date in this last line:

facebook$age <- floor(age_calc(as.Date(facebook$birthday, units = "years"))

Answer Source

I'm not sure what fails. This is what I do and it works for me:

install.packages("eeptools")
library(eeptools)

date = "06/23/1993"
date = as.POSIXct(date, tz = "", format = "%m/%d/%Y", origin="1970-01-01")

floor(age_calc(as.Date(date), units = "years"))
#[1] 23

Or without the POSIXct conversion (as per G. Grothendieck's comment):

floor(age_calc(as.Date(date, format = "%m/%d/%Y"), units = "years"))