Home > Net >  Is there an easy way to create a vector following the pattern: 1st day of the month, last day of the
Is there an easy way to create a vector following the pattern: 1st day of the month, last day of the

Time:12-02

I'm trying to find an elegant way to create a vector of dates that follows a pattern like:

x <- c(ymd("2000/01/01"), ymd("2000/01/31"), ymd("2000/02/01"), ymd("2000/02/28"))

...and so on.

So far I've just been doing this:

library(lubridate)

start <- ymd("2000/01/01")


x <- c(start, rollback(start   month(1)), 
       start   months(1), rollback(start   months(2)),
       start   months(2), rollback(start   months(3)),
       start   months(3), rollback(start   months(4)),
       start   months(4), rollback(start   months(5)),
       start   months(5), rollback(start   months(6)),
       start   months(6), rollback(start   months(7)),
       start   months(7), rollback(start   months(8)),
       start   months(8), rollback(start   months(9)),
       start   months(9), rollback(start   months(10)),
       start   months(10), rollback(start   months(11)),
       start   months(11), rollback(start   months(12)))

Any help is much appreciated, thank you!

CodePudding user response:

You could generate first days and the subtract 1:

first_days <- start   months(0:12) 
sort(c(head(first_days, -1), tail(first_days - 1, -1)))
  • Related