Likan Zhan

seq(), seq_along(), and seq_len()

Likan · 2017-11-22

This should make the difference clear. seq() acts like seq_along() except when passed a vector of length 1, in which case it acts like seq_len(). If this ever once bites you, you’ll never use seq() again!

a <- c(8, 9, 10)
b <- c(9, 10)
c <- 10

seq_along(a)
## [1] 1 2 3
seq_along(b)
## [1] 1 2
seq_along(c)
## [1] 1
seq(a)
## [1] 1 2 3
seq(b)
## [1] 1 2
seq(c)
##  [1]  1  2  3  4  5  6  7  8  9 10

It’s probably worth noting that sample() exhibits similarly crummy behavior:

sample(a)
## [1]  8  9 10
sample(b)
## [1]  9 10
sample(c)
##  [1]  1 10  3  5  2  9  6  4  7  8

Reference:

seq vs seq_along. When will using seq cause unintended results?