Calculates age in years based on a reference date, which is the system date at default.
Usage
age(x, reference = Sys.Date(), exact = FALSE, na.rm = FALSE, ...)
Arguments
- x
date(s), character (vectors) will be coerced with
as.POSIXlt()
- reference
reference date(s) (defaults to today), character (vectors) will be coerced with
as.POSIXlt()
- exact
a logical to indicate whether age calculation should be exact, i.e. with decimals. It divides the number of days of year-to-date (YTD) of
x
by the number of days in the year ofreference
(either 365 or 366).- na.rm
a logical to indicate whether missing values should be removed
- ...
arguments passed on to
as.POSIXlt()
, such asorigin
Details
Ages below 0 will be returned as NA
with a warning. Ages above 120 will only give a warning.
This function vectorises over both x
and reference
, meaning that either can have a length of 1 while the other argument has a larger length.
See also
To split ages into groups, use the age_groups()
function.
Examples
# 10 random pre-Y2K birth dates
df <- data.frame(birth_date = as.Date("2000-01-01") - runif(10) * 25000)
# add ages
df$age <- age(df$birth_date)
# add exact ages
df$age_exact <- age(df$birth_date, exact = TRUE)
# add age at millenium switch
df$age_at_y2k <- age(df$birth_date, "2000-01-01")
df
#> birth_date age age_exact age_at_y2k
#> 1 1980-09-24 42 42.37534 19
#> 2 1957-01-21 66 66.04932 42
#> 3 1935-11-17 87 87.22740 64
#> 4 1945-08-15 77 77.48493 54
#> 5 1986-04-06 36 36.84384 13
#> 6 1952-04-20 70 70.80548 47
#> 7 1985-09-08 37 37.41918 14
#> 8 1993-09-17 29 29.39452 6
#> 9 1947-07-04 75 75.60000 52
#> 10 1943-09-17 79 79.39452 56