Converting characters to dates in R

49 Views Asked by At
df = data.frame(date = c("Jan-22", "Feb-22", "Mar-23"))

where "Jan-22" means January 2022, etc.

class(df$date) returns that the values are characters rather than dates. I have tried the following to change to Date:

df$date <- as.Date(df$date)

issues

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

library(dplyr)
df$date <- df$date %>% as.character() % as.Date()

does not work either.

How can I convert this column of characters to Dates?

1

There are 1 best solutions below

0
Dan On

Try as.yearmon() function from the zoo package:

> require(zoo)
> as.yearmon(df$date, format = "%b-%y")
[1] "Jan 2022" "Feb 2022" "Mar 2023"

Then you can coerce that to Date as such:

> as.Date.yearmon(as.yearmon(df$date, format = "%b-%y"))
[1] "2022-01-01" "2022-02-01" "2023-03-01"