在循环内改变循环索引

时间:2011-05-06 14:57:52

标签: r for-loop indexing

我是R的新手。我正在使用for()循环迭代R中的向量。但是,基于某个条件,我需要跳过向量中的一些值。首先想到的是改变循环中的循环索引。我试过了,但不知怎的,它没有改变它。在R中必须有一些实现这一点。

提前致谢。 萨米

4 个答案:

答案 0 :(得分:14)

您可以在for循环中更改循环索引,但不会影响循环的执行;请参阅?"for"的详细信息部分:

 The ‘seq’ in a ‘for’ loop is evaluated at the start of the loop;
 changing it subsequently does not affect the loop. If ‘seq’ has
 length zero the body of the loop is skipped. Otherwise the
 variable ‘var’ is assigned in turn the value of each element of
 ‘seq’. You can assign to ‘var’ within the body of the loop, but
 this will not affect the next iteration. When the loop terminates,
 ‘var’ remains as a variable containing its latest value.

使用while循环代替手动索引:

i <- 1
while(i < 100) {
  # do stuff
  if(condition) {
    i <- i+3
  } else {
    i <- i+1
  }
}

答案 1 :(得分:8)

看看

?"next"

next命令将跳过循环的当前迭代的其余部分并开始下一个循环。这可能会达到你想要的效果。

答案 2 :(得分:2)

如果没有示例,很难看到你想要做什么,但你总是可以在for循环中使用if语句:

foo <- 1:10*5
for (i in seq(length(foo)))
{
 if (foo[i] != 15) print(foo[i])
}

答案 3 :(得分:2)

在R中,索引变量的局部变化在下一遍中被“纠正”:

 for (i in 1:10){
    if ( i==5 ) {i<-10000; print(i)} else{print(i)}
                 }
#-----
[1] 1
[1] 2
[1] 3
[1] 4
[1] 10000
[1] 6
[1] 7
[1] 8
[1] 9
[1] 10

由于您有一些跳过标准,您应该将标准应用于for-括在内的循环向量。 E.g:

 for( i in (1:10)[-c(3,4,6,8,9)] ) {
          print(i)}
#----
[1] 1
[1] 2
[1] 5
[1] 7
[1] 10