Search code examples
rxtszoolubridate

Calculating first and last day of month from a yearmon object


I have a simple df with a column of dates in yearmon class:

df <- structure(list(year_mon = structure(c(2015.58333333333, 2015.66666666667, 
                                  2015.75, 2015.83333333333, 2015.91666666667, 2016, 2016.08333333333, 
                                  2016.16666666667, 2016.25, 2016.33333333333), class = "yearmon")), class = c("tbl_df", 
                                                                                                               "tbl", "data.frame"), row.names = c(NA, -10L))

I'd like a simple way, preferably using base R, lubridate or xts / zoo to calculate the first and last days of each month.

I've seen other packages that do this, but I'd like to stick with the aforementioned if possible.


Solution

  • We can use

    library(dplyr)
    library(lubridate)
    library(zoo)
    df %>% 
       mutate(firstday = day(year_mon), last = day(as.Date(year_mon, frac = 1)))