R seq.Date and as.Date
seq.Date builds a sequence of calendar dates. Starting on the first day of a month gives a reliable series of month starts.
A simple example
seq.Date and as.Date
- Start with January 1, 2024
- Do this Step by one calendar month
- Result February 1, 2024
Syntax
seq(as.Date("2024-01-01"), by = "month", length.out = 3)
Run this example in R
Save the program as Lesson.R. Use R 4.x.
Rscript --vanilla Lesson.R
Generate month starts across a leap year
A reporting or booking deadline falls close to the end of a month. Use a calendar operation and validate the input so a leap day or an invalid date cannot silently shift the deadline.
starts <- seq(as.Date("2024-01-01"), by = "month", length.out = 3)
cat(paste(starts, collapse = " "), "\n", sep = "")
cat(paste(as.integer(diff(starts)), collapse = " "), "\n", sep = "")
2024-01-01 2024-02-01 2024-03-01 31 29
Subtracting successive dates yields the actual lengths of the intervening months. February 2024 contributes 29 days, so a fixed 30-day step would drift.
R documentation for seq.Date and as.Date
Schedule a new-year edition
The library publishes one bulletin on the first of each month. Step from the first of this month to the first of the next calendar month. Which date should start the next issue?
Start the spring schedule
The studio renews its timetable at the beginning of every month. Step from the first of this month to the first of the next calendar month. Which date should start the next issue?