#' Convert vectors of ages to units of years
#'
#' @param age Vector of age values (numeric)
#' @param age_unit Vector of age units ("Year(s)", "Month(s)", "Week(s)",
#' "Day(s)", or \<NA\> (case-insensitive))
#'
#' @return
#' A numeric vector of ages in years
#'
#' @examples
#' ages <- c(70, 3, 53, 61, 20, 9)
#' units <- c("Years", "Weeks", "Years", "Years", "Months", "Months")
#'
#' age_in_years(ages, units)
#'
#' @export age_in_years
age_in_years <- function(age, age_unit) {
age_unit <- tolower(age_unit)
age_unit <- gsub("[Ss]$", "", age_unit) # remove plural
valid_units <- c("year", "month", "week", "day", NA_character_)
if (!all(age_unit %in% valid_units)) {
warning("age_unit must be 'Year(s)', 'Month(s)', 'Week(s)', 'Day(s)', or ",
"<NA> (case-insensitive)")
}
mapply(age_in_years_, age, age_unit)
}
#' @noRd
age_in_years_ <- function(age, age_unit) {
switch(
age_unit,
"year" = age,
"month" = age / 12.0,
"week" = age / 52.17857,
"day" = age / 365.25,
age
)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.