coerce_dates: Coerce columns to dates, replacing unparseable values with NA

View source: R/QC_clean.R

coerce_datesR Documentation

Coerce columns to dates, replacing unparseable values with NA

Description

For each specified column, attempts to coerce the values to Date. Values that cannot be parsed (e.g. "not recorded" appearing in an otherwise date-valued column) are replaced with NA. A message lists the dropped values per column so the user is aware of what was discarded. Use suppressMessages() to silence.

Usage

coerce_dates(
  data,
  ...,
  formats = c("%Y-%m-%d", "%Y/%m/%d", "%d-%m-%Y", "%d/%m/%Y")
)

Arguments

data

A data frame, data frame extension (e.g. a tibble), or a lazy data frame (e.g. from dbplyr or dtplyr).

...

<dplyr_tidy_select> Columns to coerce. If none are supplied, data is returned unchanged.

formats

character vector of date formats to try, in order, as accepted by strptime. Default: c("%Y-%m-%d", "%Y/%m/%d", "%d-%m-%Y", "%d/%m/%Y").

Details

Columns which are already Date objects are left untouched. Date-time (POSIXct) columns are converted to Date, discarding the time of day; a message reports this, as it is a loss of information.

Dates are parsed with the formats given in formats, tried in order. The default covers the ISO 8601 form ("2020-01-15") and the common unambiguous variants. Note that formats are not guessed per value: a column is parsed with the first format which succeeds for all of its non-missing values, so mixed-format columns will report the values that did not parse.

Value

data with the specified columns coerced to Date.

See Also

coerce_numeric_vars

Examples

df <- data.frame(x = c("2020-01-15", "2020-02-30", "not recorded"),
                 y = c("a", "b", "c"))
# "2020-02-30" is not a real date and "not recorded" is not a date at all,
# so both become NA and are reported:
coerce_dates(df, x)

eHDPrep documentation built on Oct. 21, 2026, 5:10 p.m.