Question

I want to do the following nested for loop structure in R:

x<- c(a,b,c,d,e)
for(i in 1:length(x)){
  for(j in (i+1):length(x)){
     do something with (x, j)
  }
}

However, what ends up happening is that at one point j=6 (because j goes from i+1), and the loop still tries to execute and causes an out of bounds.

Of course I can always put in an if statement to check that j <= length(x) before I run the command but is there a way to do this more elegantly? For instance, in C++, I believe that the second loop would never execute...

Thank you for your help!

Was it helpful?

Solution

Try this:

for( j in seq(i + 1, length = length(x) - i) ) ...

or

for( j in i + seq_len(length(x) - i) ) ...

or

for( j in seq(i, length(x))[-1] ) ...

OTHER TIPS

The usual advice is to use seq_along:

x<- c(a,b,c,d,e)
for(i in seq_along(x)){
  for(j in seq_along( x[ -(1:i) ] ){
     do something with (x, i, j)
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top