简体   繁体   中英

R for loop termination on out of bounds

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!

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] ) ...

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)
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM