Covert R dataframe column to Date 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:
&gt; slno &lt;- c(1,2)
&gt; Date &lt;- c('22-04-2015', '4/8/2015')
&gt; 
&gt; df_data &lt;- as.data.frame(cbind(slno,Date))
&gt; df_data
  slno       Date
1    1 22-04-2015
2    2   4/8/2015
&gt; 
&gt; date_formats &lt;- c('%m/%d/%Y', '%d-%m-%Y')
&gt; 
&gt; #df_data$Date &lt;- mdy_hm(df_data$Date)
&gt; df_data$Date &lt;- as.Date(as.character(df_data$Date), tryFormats = date_formats, optional = F)
&gt; 
&gt; df_data
  slno       Date
1    1 2015-04-22
2    2       &lt;NA&gt;
&gt; str(df_data)
'data.frame':   2 obs. of  2 variables:
 $ slno: chr  "1" "2"
 $ Date: Date, format: &quot;2015-04-22&quot; ...
&gt;
The parse_date_time function from the lubridate package will do this. This function takes an argument orders which is like the tryFormats argument in 'as.Date', except the formats allowed are more generous and lubridate-like (without punctuation, delimiters, etc.). For example, you can set orders = c(&quot;dmy&quot;, &quot;mdy&quot;).
Date &lt;- c('22-04-2015', '4/8/2015')
parse_date_time(Date, orders = c(&quot;dmy&quot;, &quot;mdy&quot;))
&quot;2015-04-22 UTC&quot; &quot;2015-08-04 UTC&quot;