Seq vs seq_along. When will using seq produce unintended results?

What are (are there?) Good examples of when seq_along will work, but seq will produce unexpected results.

From the documentation ?seq we have:

Note that it dispatches the first argument class, regardless of the argument names. This can have unintended consequences if it is invoked with only one argument intending to accept it as c .: it is much better to use seg_along in this case.

+47
r seq
Dec 05
source share
2 answers

This should make the difference understandable. Basically, seq() acts like seq_along() except when passing a vector of length 1, in which case it acts like seq_len() . If you ever bite you, you will 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 may be worth noting that sample() exhibits a similar 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 
+76
Dec 05
source share

If the input for seq is equal to 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 the difference if the input is a Date vector.

 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 
+19
Dec 05
source share



All Articles