clock icon indicating copy to clipboard operation
clock copied to clipboard

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

Open DavisVaughan opened this issue 2 years ago • 1 comments
trafficstars

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 avatar Apr 18 '23 19:04 DavisVaughan

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

DavisVaughan avatar Jan 10 '24 15:01 DavisVaughan