基本“for循环”在R [英] Basic "for loop" in R

查看:176
本文介绍了基本“for循环”在R的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个关于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

为什么?

解决方案

您的循环设置了以下迭代分解的值:


  1. i <-1

    i< ; -2


    z [2] <-2

  2. i <-2

    i <-3

    z [3] <-3


  3. ...


  4. ...


  5. i <-5 < br>
    i <-6

    z [6] <-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:

    1. i<-1
      i<-2
      z[2]<-2
    2. i<-2
      i <-3
      z[3]<-3

    3. ...

    4. ...

    5. i<-5
      i<-6
      z[6]<-6

    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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆