Sam*_*ami 9 indexing for-loop r
我对R来说比较新.我正在使用for()循环迭代R中的向量.但是,基于某个条件,我需要跳过向量中的一些值.首先想到的是改变循环中的循环索引.我试过了,但不知怎的,它没有改变它.必须有一些在R中实现这一点的东西.
提前致谢.萨米
Jos*_*ich 16
您可以在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.
Run Code Online (Sandbox Code Playgroud)
请改用while循环并手动索引:
i <- 1
while(i < 100) {
# do stuff
if(condition) {
i <- i+3
} else {
i <- i+1
}
}
Run Code Online (Sandbox Code Playgroud)