I've got a dataframe that has the day of the week contained the same field as the D/M/Y, I'm trying to convert it into the traditional format without the day of the week. Dataframe format as follows:
Date: chr [1:9] "Tuesday 4 October 2022" "Wednesday 5 October 2022" "Thursday 6 October 2022"
I would have liked to simply convert that to a more usable format using:
as.Date(df&Date, format = ("%d/%m/%Y"))
But unfortunately I'm getting errors:
Error in as.Date.default(x, ...) :
do not know how to convert 'x' to class “Date”
Any advice on how to change this would be most appreciated.
CodePudding user response:
We could use parse_date
to automatically detect the format and convert to Datetime format, which is converted to Date
class with as.Date
library(parsedate)
as.Date(parse_date(str1))
[1] "2022-10-04"
Or if we want to use the base R
, make use of the correct format i.e. %A
- for the weekday, %d
- for day, %B
- for month name and %Y
- for 4-digit year
as.Date(str1, format = "%A %d %B %Y")
[1] "2022-10-04"
For the whole Date column
df$Date <- as.Date(parse_date(df$Date))
Or
df$Date <- as.Date(df$Date, format = "%A %d %B %Y")
data
str1 <- "Tuesday 4 October 2022"