Library contents

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

  1. Start with January 1, 2024
  2. Do this Step by one calendar month
  3. Result February 1, 2024
A calendar-month step moves between month starts even when months have different lengths.

Syntax

R 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.

From the programstarts <- seq(as.Date("2024-01-01"), by = "month", length.out = 3)
First output line2024-01-01 2024-02-01 2024-03-01
Lesson.R
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 = "")
Output
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

Advertisements

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?

Given1 December 2026 → next month
Worked result2027-01-01

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?

Given1 February 2024 → next month
Worked result2024-03-01