Convert Factor to Date in R (2 Examples) | Change Class of Data Object | as.Date & ymd [lubridate]

preview_player
Показать описание
R code of this video:

my_fac <- factor(c("2020-10-05", # Create example factor vector
"2022-01-07",
"2020-10-05",
"2023-11-23",
"2017-03-11"))

my_fac # Print example factor vector

my_dates1 <- as.Date(my_fac, format = "%Y-%m-%d") # Applying as.Date function
my_dates1 # Printing output to RStudio
console

class(my_dates1) # Checking class

library("lubridate")

my_dates2 <- ymd(my_fac) # Applying ymd function
my_dates2 # Printing output to RStudio console

class(my_dates2) # Checking class

Follow me on Social Media:
Рекомендации по теме
Комментарии
Автор

Hi, Thanks for the video!

My dataset has date data stored in a column as factors, just like your example above. But when I try to convert it to date type all the information turns into NAs.

Data is in format "DD-MMM-YY" and I used the code df$col <- as.Date(df$col, format = "%d-%m-%Y) to perform the convertion but as I mentioned, lost all information.

Any guess on what am I doing wrong?

Thanks !

marcelolyra
Автор

I would like to convert these dates with format YYYYMMDD to a Date class.

dates <- data.frame(Date = c("22-02-2012", "20-11-2006", "14-05-2015", "18-12-2016"))

I tried:

dates <- as.Date(dates, "%Y%m%d")

And I get the following error:

Error in as.Date.default(dates, "%Y%m%d") : do not know how to convert..
Please give solution please..

poojamahesh
Автор

hey mate, thanks for the vid.

If the date is followed by a time, will this still work? what do i add after, %Y-%m-%d? ---- %h:%m:%s?

nomad