2014-02-23 73 views
1

我不知道爲什麼這不能給我想要的結果。R在循環中意外的結果

這是我的矢量:

flowers = c("Flower", "Flower", "Vegatative", "Vegatative", "Dead") 

這裏是我的循環:

Na = 0 
for (i in 1:length(flowers)){ 
    if (i != "Dead"){ 
    Na = Na + 1 
    } 
} 
Na 

顯然娜應該等於4,但它給我的5結果當我打印花的狀態它打印所有5.我不希望它讀最後一個。我的問題是什麼?

謝謝。

+3

「i」是1到5之間的數字,它永遠不會是「死」。 –

+0

'if(flowers [i]!='Dead')' – Ananta

+1

或'for(i in flowers)'would work – rawr

回答

4

您似乎試圖計算不等於「死亡」的flowers中的值的數量。在R,要做到這一點的方法是:

sum(flowers != "Dead") 
# [1] 4 
0

在你的代碼中的錯誤是這行:

if (i != "Dead"){ 

要明白爲什麼,這將是最好打印出的i中的值循環:

for (i in 1:length(flowers)){ 
    print(i) 
} 
[1] 1 
[1] 2 
[1] 3 
[1] 4 
[1] 5 

也就是說,你迭代號(向量的索引),但實際上沒有從矢量選擇的價值,當你做了測試。要訪問值,使用flowers[i]

for (i in 1:length(flowers)){ 
    print(flowers[i]) 
} 
[1] "Flower" 
[1] "Flower" 
[1] "Vegatative" 
[1] "Vegatative" 
[1] "Dead" 

所以,回答你原來的問題是這樣的:

Na = 0 
for (i in 1:length(flowers)){ 
    if (flowers[i] != "Dead"){ 
    Na = Na + 1 
    } 
} 
Na 
[4] 

[R提供了很多做這樣的計算,而不循環設施 - 這是稱爲矢量化。關於它的一篇很好的文章是約翰庫克的5 Kinds of Subscripts in R。例如,您可能會得到如下結果:

length(flowers[flowers != "Dead"]) 
[1] 4