r-lib / clock

A Date-Time Library for R
https://clock.r-lib.org
Other
97 stars 4 forks source link

`date_parse()` (and friends) should get `failure = c("warn", "error", "NA")` #327

Open DavisVaughan opened 1 year ago

DavisVaughan commented 1 year ago

For added certainty when you know the format, or when you've wrapped it up in a function and simply can't continue if there are parse failures.

DavisVaughan commented 5 months ago

In some cases, we want to "try to parse" and detect which rows would fail to parse to identify them as "problems" (and maybe you'd throw those rows out entirely if they were problems), so we should provide some easy recipe for that, like:

library(clock)

date_parseable <- function(x,
                           ...,
                           format = NULL,
                           locale = clock_locale(),
                           missing = "allow") {
  missing <- rlang::arg_match(missing, values = c("allow", "reject"))

  # This is where we'd also make it silent, is this simply the easiest way?
  out <- suppressWarnings(
    date_parse(x, format = format, locale = locale),
    classes = "clock_warning_parse_failures"
  )

  problems <- switch(
    missing,
    allow = is.na(out) & !is.na(x),
    reject = is.na(out)
  )

  !problems
}

date_parseable(c("2019", "2020-01-01", NA))
#> [1] FALSE  TRUE  TRUE
date_parseable(c("2019", "2020-01-01", NA), missing = "reject")
#> [1] FALSE  TRUE FALSE

Providing a FAQ that does the parse and then does a check like this after the fact is probably better than exposing date_parseable() because we have so many parse variants we'd have to do it for.

It would be nice to have date_parse(failure = c("warn", "error", "NA")) where we could explicitly set "NA" for silent NA propagation