简体   繁体   English

R用于循环终止

[英]R for loop termination on out of bounds

I want to do the following nested for loop structure in R: 我想在R中执行以下嵌套的for循环结构:

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. 但是,最终发生的事情是在某一点j = 6(因为j从i + 1开始),并且循环仍然尝试执行并导致越界。

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? 当然,我总是可以在运行命令之前放入if语句来检查j <= length(x),但是有没有办法更优雅地做到这一点? For instance, in C++, I believe that the second loop would never execute... 例如,在C ++中,我相信第二个循环永远不会执行...

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: 通常的建议是使用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)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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