How to change class character to class date in R without getting NA results

I’ve got a data table with a column of dates: ex_dates <- c("2022-01-01", "2022-05-28")
they are now at class character, how can I change them to class date?

I’ve tried this code:

data$date <-  as.Date(data$date,"%d/%m/%Y")

but it changes the whole column to NA.

>Solution :

You can use lubridate package with the function YMD:

class(data$date)
[1] "character"

install.packages("lubridate")
library("lubridate")

data$date <- ymd(data$date)
class(data$date)
[1] "Date"

UPDATE without lubridate

 data$date <- as.Date(data$date, format = %m-%d-%Y)

Leave a Reply