2

Hi I have Multiple format of date in my data. How do I convert in to Date format as.posixct
Below are the sample data.

df <- data.frame(date=c('01-12-2019','44166','12-08-2019','01/27/2020'))

any help will much appreciated.

Tushar Lad
  • 490
  • 1
  • 4
  • 17

1 Answers1

2

One possibility could be to handle different date formats separately(this might be possible with the tryFormats argument in as.Date but the lack of uniformity with respect to the date formats makes it less possible to use).:

df$date <-stringr::str_replace_all(df$date,"/","-") #format won't work without this
good_formats <-df[grepl("\\D",df$date),]
bad_formats<- df[!grepl("\\D",df$date),] #They're not bad, just think they're less programmer friendly
good_formats<-as.Date(good_formats,
       format=c("%d-%m-%Y","%d-%m-%Y","%m-%d-%Y"))
bad_formats <- as.Date(as.numeric(bad_formats),origin="1970-01-01")
data.frame(date=c(good_formats,bad_formats))

Result:

   date
1 2019-12-01
2 2019-08-12
3 2020-01-27
4 2090-12-03

Structure of the result:

'data.frame':   4 obs. of  1 variable:
 $ date: Date, format: "2019-12-01" ...

Data:

data.frame(date=c('01-12-2019','44166','12-08-2019','01/27/2020')
NelsonGon
  • 13,015
  • 7
  • 27
  • 57
  • 1
    This answer also very helpful to me. Thank you every one for help. as this type of challenges may come to every one when they are working with time series data. – Tushar Lad Jan 29 '20 at 04:25