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

19,040

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])
      }
    }
Share:
19,040
Joe
Author by

Joe

Updated on June 04, 2022

Comments

  • Joe
    Joe almost 2 years

    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.