当 seq_along 工作时,但 seq 产生意外结果的例子有哪些?

什么是良好的例子,当 seq_along将工作,但 seq将产生意想不到的结果?

?seq的文档中我们可以看到:

注意,它分派第一个参数的类 无论参数名称如何,这可能有意外后果 如果调用时只有一个参数,意图将其视为 along.with: 在这种情况下使用 seq_along要好得多。

72696 次浏览

If the input to seq is length 1 then the outputs between seq and seq_along will be different

x <- 5
for(i in seq(x)){
print(x[i])
}
#[1] 5
#[1] NA
#[1] NA
#[1] NA
#[1] NA


for(i in seq_along(x)){
print(x[i])
}
#[1] 5

We also see a difference if the input is a vector of Dates

x <- Sys.Date() + 1:5
seq(x)
#Error in seq.Date(x) : 'from' must be of length 1
seq_along(x)
#[1] 1 2 3 4 5

This should make the difference clear. Basically, 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] 10  8  9
sample(b)
# [1]  9 10
sample(c)
# [1]  8  7  9  3  4  1  6 10  2  5