R - Saving the values from a For loop in a vector

2019-07-20 20:09发布

问题:

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]) }

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.

回答1:

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])
    }

Alternatively, this would work as well:

    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])
      }
    }


回答2:

I started down a similar path with rbind as @nate_edwinton did, but couldn't figure it out. I did however come up with something effective. Hmmmm, geo_mean. Cool. Coerce back to a list.

MyNums <- data.frame(x=(1:177))
a <- data.frame(x=integer())
for(i in 1:177){
  a[i,1] <- geomean(MyNums$x[1:i])
}
a<-as.list(a)