What are examples of when seq_along works, but seq produces unintended results?
Asked Answered
P

2

87

What are good examples of when seq_along will work, but seq will produce unintended results?

From the documentation of ?seq we have:

Note that it dispatches on the class of the first argument irrespective of argument names. This can have unintended consequences if it is called with just one argument intending this to be taken as along.with: it is much better to use seq_along in that case.

Project answered 5/12, 2012 at 20:43 Comment(0)
E
137

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
Evident answered 5/12, 2012 at 21:1 Comment(6)
is there an alternative to sample() then or just use as.numeric(sample(as.character(c)))?Underprivileged
@Underprivileged -- I've just used this kind of idea: safeSample <- function(x) if(length(x) == 1) x else sample(x). (Try it out with safeSample(4:5); safeSample(5).)Cheremkhovo
Sigh That sad moment when a single user has posted all the answers that you are searching for and you need to wait for 2 days to upvote fearing serial upvote script :(Pang
@BhargavRao Haha. Thanks for the compliment ;)Cheremkhovo
When applied to a empty vector, x <- c() , seq(x) and seq_along(x) both return integer(0)Covin
@EnriquePérezHerrero Seems like an appropriate return value for a zero-length vector, right?Cheremkhovo
F
26

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
Furcula answered 5/12, 2012 at 20:53 Comment(1)
that date example is great!Project

© 2022 - 2024 — McMap. All rights reserved.