as_any_date: Create objects of class "Date"

as_any_dateR Documentation

Create objects of class "Date"

Description

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.

Usage

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'.

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.

Value

A R Object of class 'Date'.

See Also

lubridate::ymd(),lubridate::ydm(),lubridate::dmy(), lubridate::myd(),lubridate::mdy(),lubridate::dym(), lubridate::my() ,lubridate::ym(), lubridate::as_date(),as.Date(), guess_date_format(),which_any_date()

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))

}


fabR documentation built on May 29, 2024, 2:58 a.m.