seq() and the : Operator (R)
seq() generates regular sequences of numbers, and the colon operator a:b creates a sequence of consecutive integers from a to b. Both are core tools for building index and value vectors.
R
The colon operator is the quick form: 1:5 gives c(1, 2, 3, 4, 5), and it counts down too (5:1). seq() is the flexible form, letting you specify a step with by (seq(0, 10, by = 2)) or a total count with length.out (seq(0, 1, length.out = 5)). seq_len(n) and seq_along(x) safely generate indices for loops.
A common pitfall: 1:length(x) misbehaves when x is empty (length 0), because 1:0 produces c(1, 0) rather than nothing. Using seq_len(length(x)) or seq_along(x) avoids that bug, which is why they're preferred for iteration bounds.
These sequence tools pair with indexing and the apply family to drive vectorized work. They're how you build the ranges, axes, and index vectors that show up throughout R code.
Syntax
1:10
seq(0, 1, by = 0.25)
seq_along(x)Examples
R
print(1:5)
print(seq(0, 10, by = 2))
print(seq(0, 1, length.out = 5))Output:
[1] 1 2 3 4 5
[1] 0 2 4 6 8 10
[1] 0.00 0.25 0.50 0.75 1.00