Neil Neil - 3 months ago 9
R Question

Converting Character to Date in R

I have a dataframe in R which has date column as character. When I try to convert it into date with following code it gives me an error.

No First Landing Page Submission Date
1
2
3 31-07-2016 16:57
4 31-07-2016 16:38
5 1/8/2016 4:58
6
7 31-07-2016 15:40
8
9 31-07-2016 14:49
10
11 31-07-2016 14:41
12 31-07-2016 13:51


Data is exactly in above format in csv file.

df$First.Landing.Page.Submission.Date <- as.Date(df$First.Landing.Page.Submission.Date)


It gives me following error.

Error in charToDate(x) :
character string is not in a standard unambiguous format


When I use parsing function from lubridate package it gives me coversion of this form.

df$First.Landing.Page.Submission.Date <- parse_date_time(df$First.Landing.Page.Submission.Date, orders="dmy hms")

No First.Landing.Page.Submission.Date
1 <NA>
2 <NA>
3 2020-07-31 16:16:57
4 2020-07-31 16:16:38
5 2020-08-01 16:04:58
6 <NA>


If you look at 3rd row original date is 31-07-2016 16:57 and when I parsed it became 2020-07-31 16:16:57. Can you please tell me the correct way to do it.

Answer

You can use lubridate's dmy_hms function with the option truncated=1

lubridate::dmy_hms(df1$FirstLanding, truncated = 1)

This option is helpful when the data is not complete. In this particular case, the seconds are missing which would be required for a DMY-HMS format.

Comments