Search code examples
rlubridate

R class changes after lubridate


I'm trying to use lubridate to extract the month of a date but the class changes. Here is an example of my code

library(lubridate)
mydates<-c("10-10-2020","11-10-2020")
mydates <- as.Date(mydates,"%m-%d-%Y")
class(mydates)
mydates <- month(mydates, label=TRUE)
class(mydates)

I would like to continue to have it as a class date but I'm unable too. This is to plot the chart as a date. Any advice? Thanks,


Solution

  • It looks like you want to use floor_date to convert to the first date of the month.

    floor_date(mydates, unit = "months")
    

    This way Dec 2020 will occur before Jan 2021 because you still have an actual date.

    If you only want to show the month name in the axis, then this is a question about the plot labels, not lubridate.