R-将For循环中的值保存在向量或列表中 [英] R - Saving the values from a For loop in a vector or list

查看:631
本文介绍了R-将For循环中的值保存在向量或列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将此for循环的每次迭代保存在向量中.

I'm trying to save each iteration of this for loop in a vector.

for (i in 1:177) { a <- geomean(er1$CW[1:i]) }

for (i in 1:177) { a <- geomean(er1$CW[1:i]) }

基本上,我有177个值的列表,我希望脚本查找列表的累积几何平均值.现在,它只会给我最终值,不会将每次循环迭代另存为列表或向量中的单独值.

Basically, I have a list of 177 values and I'd like the script to find the cumulative geometric mean of the list going one by one. Right now it will only give me the final value, it won't save each loop iteration as a separate value in a list or vector.

推荐答案

您的代码不起作用的原因是对象a在每次迭代中均被覆盖.例如,以下代码精确地完成了您想要的工作:

The reason your code does not work is that the object ais overwritten in each iteration. The following code for instance does what precisely what you desire:

    a <- c()
    for(i in 1:177){
      a[i] <- geomean(er1$CW[1:i])
    }

或者,这也可以工作:

    for(i in 1:177){
      if(i != 1){
      a <- rbind(a, geomean(er1$CW[1:i]))
      }
      if(i == 1){
        a <- geomean(er1$CW[1:i])
      }
    }

这篇关于R-将For循环中的值保存在向量或列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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