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
. i.e anytime::anydate("1995")