age_calculate: Calculate age between two dates

View source: R/age_calculate.R

age_calculateR Documentation

Calculate age between two dates

Description

This function calculates the age between two dates using functions in lubridate. It calculates age in either years or months.

Usage

age_calculate(
  start,
  end = if (lubridate::is.Date(start)) Sys.Date() else Sys.time(),
  units = c("years", "months"),
  round_down = TRUE
)

Arguments

start

A start date (e.g. date of birth) which must be supplied with Date or POSIXct or POSIXlt class. base::as.Date(), lubridate::dmy() and as.POSIXct() are examples of functions which can be used to store dates as an appropriate class.

end

An end date which must be supplied with Date or POSIXct or POSIXlt class. Default is Sys.Date() or Sys.time() depending on the class of start.

units

Type of units to be used. years and months are accepted. Default is years.

round_down

Should returned ages be rounded down to the nearest whole number. Default is TRUE.

Value

A numeric vector representing the ages in the given units.

Examples

library(lubridate)
birth_date <- lubridate::ymd("2020-02-29")
end_date <- lubridate::ymd("2022-02-21")
age_calculate(birth_date, end_date)
age_calculate(birth_date, end_date, units = "months")

# If the start day is leap day (February 29th), age increases on 1st March
# every year.
leap1 <- lubridate::ymd("2020-02-29")
leap2 <- lubridate::ymd("2022-02-28")
leap3 <- lubridate::ymd("2022-03-01")

age_calculate(leap1, leap2)
age_calculate(leap1, leap3)

Health-SocialCare-Scotland/phsmethods documentation built on Jan. 28, 2024, 3:18 a.m.