1

Suppose I got a vector that looks like this:

dates <- c("2/11/2021","2/17/2021","2/26/2021","2/7/2021" ,"3/12/2021","3/18/2021","3/2/2021")

When trying to convert to Date with as.Date(dates, format = "%d/%m/%Y"), I've got some NA's:

#"2021-11-02" 
#NA           
#NA           
#"2021-07-02" "2021-12-03" 
#NA          
#"2021-02-03"

Expected Output could look like this:

#"2021-11-02" 
#"2021-02-17"           
#"2021-02-16"           
#"2021-07-02" 
#"2021-12-03" 
#"2021-18-03"          
#"2021-02-03"

Is there any way to convert all elements to .Date() class?

AlSub
  • 1,384
  • 1
  • 14
  • 33

1 Answers1

1

We can use anydate from anytime

anytime::anydate(dates)
#[1] "2021-02-11" 
#[2]"2021-02-17"
#[3] "2021-02-26" 
#[4] "2021-02-07" 
#[5] "2021-03-12"
#[6] "2021-03-18" 
#[7] "2021-03-02"

With as.Date, the format would be %m/%d/%Y

as.Date(dates, format = "%m/%d/%Y")
#[1] "2021-02-11" "2021-02-17" "2021-02-26" "2021-02-07" "2021-03-12" "2021-03-18" "2021-03-02"
akrun
  • 874,273
  • 37
  • 540
  • 662