This function takes a character string or a vector. This vector is evaluates one observation after the other, and casts the best matching date format for each of them (independently). The best matching format is tested across seven different formats provided by the lubridate library. The user can specify the wanted matching format (and can be helped using which_any_date() for each value or guess_date_format() for the values as a whole.

as_any_date(
  x = as.character(),
  format = c("dmy", "dym", "ymd", "ydm", "mdy", "myd", "my", "ym", "as_date")
)

Arguments

x

object to be coerced.

format

A character identifying the format to apply to the object. That format can be 'ymd','ydm','dym','dmy','mdy','myd','my','ym'.

Value

A R Object of class 'Date'.

Details

Contrary to lubridate library or as.Date(), the function evaluates the different possibilities for a date. For example, c('02-03-1982') can be either March the 2nd or February the 3rd. The function will cast the value as NA, and a warning, since there is an ambiguity that cannot be solved, unless the user provides the format to apply.

Examples

{

library(dplyr)
library(tidyr)

##### Example 1 -------------------------------------------------------------
# Ambiguous dates -----------------------------------------------------------
as_any_date('19 02 12')
as_any_date('19 02 12', format = "ymd")
as_any_date('19 02 12', format = "dym")

##### Example 2 -------------------------------------------------------------
# Non-ambiguous dates -------------------------------------------------------
time <-
  tibble(time = c(
  "1983 07-19",
  "14-01-1925",
  "12/13/2015",
  "2009-09-13",
  "17-12-12",
  "coucou",
  "2025 jan the 30th",
  "1809-01-19"))

time %>% mutate(new_time = as_any_date(time))

}
#> Warning: There was 1 warning in `mutate()`.
#>  In argument: `new_time = as_any_date(time)`.
#> Caused by warning:
#> ! All formats failed to parse for some values.
#> 
#> 
#> Useful tip: Use which_any_date(x) to get formats.
#> # A tibble: 8 × 2
#>   time              new_time  
#>   <chr>             <date>    
#> 1 1983 07-19        1983-07-19
#> 2 14-01-1925        1925-01-14
#> 3 12/13/2015        2015-12-13
#> 4 2009-09-13        2009-09-13
#> 5 17-12-12          2017-12-12
#> 6 coucou            NA        
#> 7 2025 jan the 30th 2025-01-30
#> 8 1809-01-19        1809-01-19