How to Extract a Month from a Date in R (Example) | as.Date, class & format Functions | Get Months

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

x <- "2022-10-05" # Create example date
x # Print date

x_formatted <- as.Date(x, format = "%Y-%m-%d") # Convert character to Date
x_formatted # Print Date object

class(x_formatted) # Checking class

x_month <- format(x_formatted, "%m") # Extract month
x_month # Print month

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

Thanks. I have opened your website. Thanks for sharing this topics. Cheers from Brazil

HenriqueSantos-xdeg
Автор

Dear, How to arrange the code to have the class of x_month also as a "Date"?

celineherst
Автор

doesnt work Error in parse.format(format[1]) : unrecognized format %m, I have a list of dates, not a single date

richardyeung
Автор

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