calculate age in R with lubridate

How to calculate age in R

Here is how to calculate age in R in a way that humans understand it. If someone has a birthday on 2000-01-01 and today is 2021-07-09, then that person is 21 years old.

The easiest and most accurate method to calculate age in R is by using the lubridate package.

Calculate age in R with lubridate

birth_date <- as.Date("1973-01-01")
x_date   <- as.Date("2019-01-01")


require(lubridate)

trunc((birth_date %--% x_date) / years(1))

#[1] 46

Operator %–% creates a time interval from the date of the birth to a specified date, and that is divided with a 1-year period by using function years.

It is fas enough even in large datasets that have a couple of million age calculations. Even if your data contains NA values, that is not a problem and does not cause an error. That might not be the case for calculating age_calc from the eeptools package.

Other calculations

Sometimes there is an approach that using only base R, but it is approximate.
Here is an example with results that we get with lubridate and the other two popular methods.

birth_date <- as.Date("1973-01-01")
x_date   <- as.Date("2019-01-01")

trunc(as.numeric(difftime(x_date, birth_date, units = "days")) / 365.25)
#[1] 45
trunc(as.numeric(difftime(x_date, birth_date, units = "weeks")) / 52.25)
#[1] 45
require(lubridate)
trunc((birth_date %--% x_date) / years(1))
#[1] 46

Most of the time, results will be the same for all these methods. But if you want a precise result, the choice is obvious.

 

If you are an Excel user, age calculation in R with lubridate is a good alternative to the same calculation with function DATEDIF.

If you want to compare results with something in Excel, here is how to copy data from R to Excel.





Posted

in

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *