#' Calculate age in years from dates of birth
#'
#' @description
#' Calculate age in years from dates of birth.
#'
#' @param dob Vector of dates of birth. If not of class "Date", will attempt to
#' convert using \code{\link[lubridate:as_date]{lubridate::as_date}}.
#' @param until End-date used for age calculation. Defaults to current date
#' (based on `Sys.Date()`). If not of class "Date", will attempt to convert
#' using \code{\link[lubridate:as_date]{lubridate::as_date}}.
#' @param as_int Logical indicating whether to return ages rounded down to the
#' nearest integer (`TRUE`), or as numeric decimal values (`FALSE`). Defaults
#' to `TRUE`.
#'
#' @return
#' Vector of ages in units of years, either of class integer (if `as_int =
#' TRUE`) or numeric (`as_int = FALSE`).
#'
#' @examples
#' dates_of_birth <- as.Date(
#' c("2001-04-05", "1976-10-24", "1990-03-15", "1943-12-08")
#' )
#'
#' # by default returns integer ages
#' age_from_dob(dates_of_birth)
#'
#' # use as_int = FALSE to return decimal values
#' age_from_dob(dates_of_birth, as_int = FALSE)
#'
#' # calculate with end-point other than current date
#' age_from_dob(dates_of_birth, until = "2019-01-01")
#'
#' @importFrom lubridate interval as_date
#' @export age_from_dob
age_from_dob <- function(dob,
until = Sys.Date(),
as_int = TRUE) {
if (!"Date" %in% class(dob)) dob <- lubridate::as_date(dob)
if (!"Date" %in% class(until)) until <- lubridate::as_date(until)
time_interval <- lubridate::interval(dob, until)
age <- as.numeric(time_interval, "years")
if (as_int) age <- as.integer(floor(age))
age
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.