Joe
Joe

Reputation: 63

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

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.

Upvotes: 4

Views: 23119

Answers (3)

ExHunter
ExHunter

Reputation: 307

you can try to define the variable that can save the result first

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

Upvotes: 0

Scottieie
Scottieie

Reputation: 324

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)

Upvotes: 0

niko
niko

Reputation: 5281

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

Upvotes: 8

Related Questions