How to calculate age from birthdate and timestamp in r?

Viewed 84

I have the following dataframe:

birthdate <- c("1993-06-27","1977-11-15","1988-08-12","1981-03-01")
timestamp <- c("2020-07-01 16:35:52","2020-07-01 16:48:55","2020-07-01 
16:53:42","2020-07-01 16:42:58")
df <- data.frame(birthdate,timestamp)

Based on these two columns (birthdate and completition date), I would like to calculate the age value for each id.

2 Answers
library(dplyr)                 
library(lubridate)
id <- data.frame(birthdate= parse_date_time(c("1993-06-27","1977-11-15",
                                            "1988-08-12","1981-03-01",
                                            "1988-04-04"), '%Y-%m-%d'),
                 timestamp=parse_date_time(c("2020-07-01 16:35:52","2020-07-01 16:48:55",
                                             "2020-07-01 16:53:42","2020-07-01 16:42:58",
                                             "2020-07-01 16:45:50"), '%Y-%m-%d %H:%M:%S'))

id<-id %>% mutate(age = as.numeric(difftime(timestamp,birthdate, units="weeks")/52))

Gives us

> id
   birthdate           timestamp      age
1 1993-06-27 2020-07-01 16:35:52 27.10630
2 1977-11-15 2020-07-01 16:48:55 42.77390
3 1988-08-12 2020-07-01 16:53:42 31.99644
4 1981-03-01 2020-07-01 16:42:58 39.47169
5 1988-04-04 2020-07-01 16:45:50 32.35357

We can use difftime

with(df1, as.numeric(difftime(timestamp, birthdate, units = 'weeks')/52))
Related