I want to loop over a range of numbers from 1:n
, when n
is the length of vector v
in R. Usually, I would use the for (i in 1:length(v))
syntax, but this fails when n == 0
.
What is the idiomatic way to do this loop? At the moment I do the followin, but it seems a little ugly:
# This is in my standard library
rng <- function(n)seq(from=1, to=n, length.out=n)
# Now when I come to the for loop:
for(i in rng(length(v))){
print(paste("I ate", i, "kg of brocolli today"))
}
And yes, I know its better to vectorise, but there are situations when vectorisation isn't possible or would require so much extra work that it is much harder to read the code.
It would be better to use seq_along
:
> v <- letters[1:3]
> for (i in seq_along(v)) print(c(i, v[i]))
[1] "1" "a"
[1] "2" "b"
[1] "3" "c"
>
> v <- numeric(0)
> for (i in seq_along(v)) print(c(i, v[i]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With