2011-05-06 163 views
7

我對R相對較新。我通過for()循環遍歷R中的一個向量。但是,基於某種條件,我需要跳過向量中的一些值。想到的第一個想法是改變循環內的循環索引。我嘗試過,但不知怎的,它沒有改變它。必須有一些什麼在R實現這一點。更改循環內的循環索引

在此先感謝。 薩米

+0

薩米 - 你可以發佈一些樣本數據? – Chase 2011-05-06 15:07:34

+0

請給我們一些示例代碼... – EDi 2011-05-06 15:08:11

+0

它可能會改變循環內的索引,但更改的值不會更改下一個傳遞的索引。控制層面的索引不受當地索引變量的影響。 – 2011-05-06 15:09:42

回答

9

可以內改變循環索引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

您可以在for循環中更改索引變量,但不會「粘住」。 – 2011-05-06 15:15:39

+0

@DWin:同意。我的意思是OP的意思是「改變」 - 跳過價值。 – 2011-05-06 15:18:10

2

沒有一個例子是很難看到你想要做什麼,而是你可以一直使用裏面一個for循環的if語句:

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

由於您有一些跳過的標準,因此您應該將標準應用於圓括號內的循環向量。 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 
+0

通過'seq'參數跳過for循環假設您先驗知道哪些元素跳過。如果是這種情況,您可以使用矢量化解決方案並完全跳過循環。 – 2011-05-06 16:03:25

8

?"next" 

next命令將跳過循環的當前迭代的休息,並開始下一個。這可能會達到你想要的。