How to formulate a for in loop in R, where can I request zero points?

I want to iterate over a range of numbers from 1:n when n is the length of the vector v in R. Usually I use the syntax for (i in 1:length(v)) , but this fails if n == 0 .

What is the idiomatic way to do this loop? At the moment, I am doing the following, 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 it better for vectorization, but there are situations when vectorization is impossible or will require so much additional work that reading the code is much more difficult.

+6
source share
1 answer

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])) 
+12
source

Source: https://habr.com/ru/post/918429/


All Articles