0

In the same column, I have dates under the format ddmmyyyy and dd/mm/yyyy. The column is of class character. I would like to convert the dates under the format date.

This is pretty easy separately. But I do not understand how to convert them both.

Another problem I have is that when there is no date at certain rows, it does not appear as "NA" (I also checked with the function is_empty())... So, I cannot separate the dates in two different columns.

Here is what my dataset looks like :

date = c("22102002", "23122002", "23/12/02", "29/12/03", ""   ,"04/06/04") 
as.data.frame(date)

So I have :

date 
22102002
23122002
23/12/02
29/12/03

04/06/04

and I would like :

true_date
22/10/2002
23/12/2002
23/12/02
29/12/03
NA
04/06/04

Thank you for your answers!

Emeline
  • 161
  • 9

1 Answers1

2

We can use parse_date_time from lubridate.

date = c("22102002", "23122002", "23/12/02", "29/12/03", ""   ,"04/06/04") 
as.Date(lubridate::parse_date_time(date, c('dmY', 'dmy')))
#[1] "2002-10-22" "2002-12-23" "2002-12-23" "2003-12-29" NA           "2004-06-04"
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213