基本“for循环”在R [英] Basic "for loop" in R
问题描述
i <-0
z <-numeric(6)
for(i在1:5中){
i <-i + 1
z [i] <-i
}
我希望输出是
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ ] 1 2 3 4 5 6
但它生成了
> z
[1] 0 2 3 4 5 6
为什么?
您的循环设置了以下迭代分解的值:
-
i <-1
i< ; -2
z [2] <-2
-
i <-2
i <-3
z [3] <-3
-
...
-
...
-
i <-5
< br>
i <-6
z [6] <-6
i<-1
i<-2
z[2]<-2
i<-2
i <-3
z[3]<-3
...
...
i<-5
i<-6
z[6]<-6
正如您所见, z [1]
从来没有设置,因为你增加了我
befo重新使用它作为索引。将循环更改为 z [i] <-i
,而不是别的。此外,将循环设置为从 1
到 6
而不是 5
如果你想设置 6
元素:
z< ; -numeric(6)
for(i in 1:6){
z [i] <-i
}
i have a basic problem about for loop for R. But i can't understand. it's my code.
i<-0
z<-numeric(6)
for(i in 1:5){
i<-i+1
z[i]<-i
}
i want the output to be
>z
[1] 1 2 3 4 5 6
but it generated
>z
[1] 0 2 3 4 5 6
why?
Your loop sets the following values, broken down by iteration:
As you can see, z[1]
is never set because you increment i
before using it as an index. Change the loop to just do z[i]<-i
and nothing else. Also, set the loop to run from 1
to 6
instead of to 5
if you want to set 6
elements:
z<-numeric(6)
for(i in 1:6){
z[i]<-i
}
这篇关于基本“for循环”在R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!