A kinder way to suppress warnings in lubridate::as_date()?

Are there any clean ways to suppress warnings in lubridate::as_date() besides suppressWarnings()? There doesn't seem to be a quiet = TRUE argument in lubridate::as_date() like there is in lubridate::mdy()

By the way, I'm totally fine with the NAs here. It's the warning messages -- All formats failed to parse. No formats found -- that bother me.

Reprex if you're interested:

library(lubridate)

# NA but with warnings
lubridate::as_date("1995")
#> Warning: All formats failed to parse. No formats found.
#> [1] NA

# Bad method but fine output (no warnings)
suppressWarnings(lubridate::as_date("1995"))
#> [1] NA

Created on 2018-08-25 by the reprex package (v0.2.0).

1 Like

I do not know of another way but I am not sure why you are fine with NA. When working with date, the better practice is to correctly parse them to avoid errors in the mid/long term. And bonus when doing that, no warning. Warning here help you know that something is not fine.

However, if you keep on going with this, you can just wrap your function:

as_date <- function(x, quiet = FALSE, ...) {
  if (quiet) {
    suppressWarnings(lubridate::as_date(x, ...))
  } else {
    lubridate::as_date(x, ...)
  }
}
as_date("1995")
#> Warning: All formats failed to parse. No formats found.
#> [1] NA
as_date("1995", quiet = TRUE)
#> [1] NA

There are also other packages dedicated to time conversion that helps with multiple format like anytime :package:. i.e anytime::anydate("1995")

4 Likes

Thanks for the response. I'm fine with NAs here because I'm only trying to parse dates in the YYYY-MM-DD format, so anything other than that may as well be an NA for me.

Yeah, so, since usually you wouldn't try to convert something to a date unless you want it converted to a date, you'll have to add a workaround (essentially, it's noisy on purpose— it's not doing what you're asking it to). You might even want to filter anything that doesn't match the YYYY-MM-DD format you're looking for.

For example, you could use the regular expression below to see whether the format is TRUE or FALSE:

grepl("[12]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\\d|3[01])", **STRING OR CHAR VEC**)
2 Likes