Back to Blog
2 min read

How to Calculate Age in R (lubridate and Date Logic Examples)

Learn how to calculate age from date of birth in R using base Date logic and lubridate, with a reliable birthday check.

How to Calculate Age in R (lubridate and Date Logic Examples)

How to Calculate Age in R (lubridate and Date Logic Examples)

In R, age usually means the number of completed years. The safest pattern is simple: subtract the birth year, then reduce by one if the birthday has not happened yet in the reference year.

Fast option: use an online age calculator

If you want a quick check, or you need an exact result in years, months, and days, verify the dates in a calculator first and then mirror the logic in code.

Open the age calculator and enter the date of birth plus the reference date.

Base R example

This version works with Date values and returns completed years.

age_years <- function(dob, as_of = Sys.Date()) {
  dob <- as.Date(dob)
  as_of <- as.Date(as_of)

  years <- as.integer(format(as_of, "%Y")) - as.integer(format(dob, "%Y"))
  had_birthday <- format(as_of, "%m-%d") >= format(dob, "%m-%d")

  if (!had_birthday) years <- years - 1
  years
}

age_years("1994-09-12")

Using lubridate

lubridate can make date handling clearer, but the key birthday check is still the same.

library(lubridate)

age_years_lubridate <- function(dob, as_of = today()) {
  dob <- ymd(dob)
  as_of <- ymd(as_of)

  years <- year(as_of) - year(dob)
  had_birthday <- sprintf("%02d-%02d", month(as_of), mday(as_of)) >=
    sprintf("%02d-%02d", month(dob), mday(dob))

  if (!had_birthday) years <- years - 1
  years
}

FAQ

Can I divide days by 365.25?

You can for a rough estimate, but it is not the best choice for real age because birthdays and leap years create off-by-one problems. A birthday check is more reliable.

What about exact age in years, months, and days?

That requires careful unit subtraction because months have different lengths. For testing, it helps to compare your result with a dedicated calculator.

Related