Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I formulate a for in loop in R where I may want to loop zero times?

Tags:

idioms

for-loop

r

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.

like image 210
fmark Avatar asked Jun 19 '12 02:06

fmark


1 Answers

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]))
like image 91
kohske Avatar answered Sep 28 '22 07:09

kohske