How to Create a Sequence of Dates in R

04.30.2021

R provides a simple way to create sequences of dates. Using the generic seq function, we can support dates and many date sequence options. In this article, we will learn how to create a sequence of dates in R.

We can create a sequence between two dates by usging the to, from, and by options in the seq method. The by optional will be used a the number of days by default.

start = as.Date("2021-04-01")
end = as.Date("2029-05-01")
seq(from = start, to = end, by = 1)

# [1] "2021-04-01" "2021-04-02" "2021-04-03" "2021-04-04" "2021-04-05" "2021-04-06" "2021-04-07" "2021-04-08" "2021-04-09"
# [10] "2021-04-10" "2021-04-11" "2021-04-12" "2021-04-13" "2021-04-14" "2021-04-15" "2021-04-16" "2021-04-17" "2021-04-18"
# [19] "2021-04-19" "2021-04-20" "2021-04-21" "2021-04-22" "2021-04-23" "2021-04-24" "2021-04-25" "2021-04-26" "2021-04-27"
# [28] "2021-04-28" "2021-04-29" "2021-04-30" "2021-05-01"

We can also use the length.out paramter to specify a generic time frame out. Additonally, we can use different options for the by paramter so we can specify to increment by days, weeks, months or years.

start = as.Date("2021-04-01")

# 7 days out
seq(from = start, by = 1, length.out = 7)
# [1] "2021-04-01" "2021-04-02" "2021-04-03" "2021-04-04" "2021-04-05" "2021-04-06" "2021-04-07"

# 3 months out
seq(from = start, by = "month", length.out = 3)
# [1] "2021-04-01" "2021-05-01" "2021-06-01"

# 4, 3 month increments. Or 4 quarters of the year
seq(from = start, by = "3 month", length.out = 4)
# [1] "2021-04-01" "2021-07-01" "2021-10-01" "2022-01-01"

# 2 weeks out
seq(from = start, by = "week", length.out = 3)
# [1] "2021-04-01" "2021-04-08" "2021-04-15"

# 2 years out
seq(from = start, by = "year", length.out = 3)
# [1] "2021-04-01" "2022-04-01" "2023-04-01"