Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there an easy way to create a vector following the pattern: 1st day of the month, last day of the month, 1st day of the month etc.?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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)))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading