Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading