How to Create Sequences of Numbers in R
To create sequences of numbers in R, the seq() function is the workhorse: it handles fixed steps, specific lengths, and along-another-vector patterns. This is one of the most common R operations, whether you are generating index variables, setting up grid points, or repeating patterns. Understanding seq() arguments saves you from subtle bugs with the colon operator.
# Integer sequence with step
seq(1, 10, by = 2) # 1 3 5 7 9
# Fixed number of points between bounds
seq(1, 5, length.out = 10)
# Along the indices of another vector
x <- c("a", "b", "c")
seq_along(x) # 1 2 3
Always prefer seq_len(n) over the colon operator 1:n when n could be zero. 1:0 produces the buggy c(1, 0) while seq_len(0) correctly returns integer(0). For repeated values, rep(c(1, 2), each = 3) gives 1 1 1 2 2 2 and rep(c(1, 2), times = 3) gives 1 2 1 2 1 2. The length.out argument is handy for creating evenly spaced points: seq(0, 1, length.out = 5) produces 0.00 0.25 0.50 0.75 1.00. Use along.with to match the length of an existing vector: seq(0, 10, along.with = existing_vec) creates a sequence with exactly length(existing_vec) points spanning the specified range. For date sequences, seq.Date(from = as.Date("2026-01-01"), to = as.Date("2026-01-31"), by = "week") generates weekly intervals and respects calendar boundaries correctly. The from and to arguments also accept character strings that are coerced to Date automatically.
# Safer alternative to 1:n
seq_len(5) # 1 2 3 4 5
seq_len(0) # integer(0) — no bug
# The colon operator for quick integer ranges
1:10 # 1 2 3 4 5 6 7 8 9 10