[Hadley pointed this out in a comment.]
When using a sequence as an index for iteration, it's better to use the seq_along()
function rather than something like 1:length(x)
.
Here I create a vector and both approaches return the same thing:
> x <- 1:10
> 1:length(x)
[1] 1 2 3 4 5 6 7 8 9 10
> seq_along(x)
[1] 1 2 3 4 5 6 7 8 9 10
Now make the vector NULL
:
> x <- NULL
> seq_along(x) # returns an empty integer; good behavior
integer(0)
> 1:length(x) # wraps around and returns a sequence; this is bad
[1] 1 0
This can cause some confusion in a loop:
> for(i in 1:length(x)) print(i)
[1] 1
[1] 0
> for(i in seq_along(x)) print(i)
>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…