seq()
seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)), length.out = NULL, along.with = NULL) Returns:
numeric · Updated March 13, 2026 · Base Functions sequence numbers base
seq() creates sequences of numbers with precise control over start, end, length, and step size. It’s essential for looping, creating index vectors, and generating test data.
Syntax
seq(from = 1, to = 1, by = ((to - from)/(length.out - 1)), length.out = NULL, along.with = NULL)
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
from | numeric | 1 | Starting value of the sequence |
to | numeric | 1 | Ending value (inclusive) |
by | numeric | (to-from)/(length.out-1) | Step size (increment) |
length.out | integer | NULL | Desired length of the sequence |
along.with | vector | NULL | Take length from this object |
Examples
Basic sequence from 1 to 10
seq(1, 10)
# [1] 1 2 3 4 5 6 7 8 9 10
Sequence with custom increment
seq(0, 100, by = 10)
# [1] 0 10 20 30 40 50 60 70 80 90 100
seq(1, 9, by = 2)
# [1] 1 3 5 7 9
Sequence with specified length
seq(0, 1, length.out = 5)
# [1] 0.00 0.25 0.50 0.75 1.00
seq(0, 10, length.out = 3)
# [1] 0 5 10
Using along.with to match another vector’s length
x <- c("a", "b", "c", "d")
seq(along.with = x)
# [1] 1 2 3 4
seq(10, 50, along.with = x)
# [1] 10 23 36 50
Negative sequences
seq(10, 1, by = -1)
# [1] 10 9 8 7 6 5 4 3 2 1
seq(5, -5, length.out = 11)
# [1] 5 4 3 2 1 0 -1 -2 -3 -4 -5
Fractional sequences
seq(0, 1, by = 0.1)
# [1] 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1.0
Common Patterns
Creating index vectors for loops
n <- 5
for (i in seq_len(n)) {
print(i)
}
# [1] 1
# [1] 2
# [1] 3
# [1] 4
# [1] 5
Generating test data frames
df <- data.frame(
id = seq(1, 100),
value = seq(0, 99) ^ 2
)
head(df)
# id value
# 1 1 0
# 2 2 1
# 3 3 4
# 4 4 9
# 5 5 16
# 6 6 25
Creating time-based sequences
# Daily sequence for a week
seq(as.Date("2026-01-01"), as.Date("2026-01-07"), by = "day")
# [1] "2026-01-01" "2026-01-02" "2026-01-03" "2026-01-04" "2026-01-05"
# [6] "2026-01-06" "2026-01-07"
Reproducible sequences with set.seed
set.seed(42)
seq_len(5) + sample(0:10, 5)
# [1] 3 8 12 7 11