Search code examples
rlubridate

Change date to the last day of month using days_in_month


I have a character variable and I want to change it to a variable of class Date and change it to the last day of the month using days_in_month().

My character variable is currently in the form Year-Mo, e.g. 2017-01, 2017-02.

How would I do this using as.Date and days_in_month


Solution

  • This is a great question, because it's been asked many times! Check out these answers:

    R calculate month end

    Create end of the month date from a date variable

    The great part? Packages update all the time, so sometimes the answers no longer work. That's not the case here.

    @Edgar Santos, at the first link, gave a detailed answer that fits your question perfectly.

    library(lubridate)
    
    dt <- c("2017-01","2017-02")  # data
    dt <- ym(dt)                  # change to date of year-month format
    day(dt) <- days_in_month(dt)  # update the 'day' in the date
    
    [1] "2017-01-31" "2017-02-28"