I have a R dataframe having a column with dates in multiple formats. I want to convert this column to date format.
While some formats are converted others are not. Why is the second date not converted? How can this be corrected?
Code and result:
> slno <- c(1,2)
> Date <- c('22-04-2015', '4/8/2015')
>
> df_data <- as.data.frame(cbind(slno,Date))
> df_data
slno Date
1 1 22-04-2015
2 2 4/8/2015
>
> date_formats <- c('%m/%d/%Y', '%d-%m-%Y')
>
> #df_data$Date <- mdy_hm(df_data$Date)
> df_data$Date <- as.Date(as.character(df_data$Date), tryFormats = date_formats, optional = F)
>
> df_data
slno Date
1 1 2015-04-22
2 2 <NA>
> str(df_data)
'data.frame': 2 obs. of 2 variables:
$ slno: chr "1" "2"
$ Date: Date, format: "2015-04-22" ...
>