'How do I save the output of a nested for-loop in separate lists?

I have the following code The result is the list pars with 9 elements with 2 elements in each.

How can I make it so that it saves a list after each loop resulting in 9 separate lists?


for (i in 1:9) {

for (d in c(0.5,1,2)){

for (a in c(0.05,0.1,0.2)){

avalues<-c(rnorm(5,mean=1, sd=a))

dvalues<-c(rnorm(5,mean=0, sd=d))

pars[[i]]<-list(avalues,dvalues)
}

}

}




Solution 1:[1]

Is this what you want?

  pars <- list()
    for (i in 1:9) {
      
      for (d in c(0.5,1,2)){
        
        for (a in c(0.05,0.1,0.2)){
          
          avalues<-c(rnorm(5,mean=1, sd=a))
          
          dvalues<-c(rnorm(5,mean=0, sd=d))
          
          pars[[i]]<-cbind(avalues,dvalues)
        }
        
      }
      
    }
    pars

Then you get 9 list, each containing two columns and five rows e.g.

[[1]]
       avalues    dvalues
[1,] 1.2623579  0.2366536
[2,] 1.2916144  3.3522442
[3,] 0.8215570 -0.0652520
[4,] 0.9696018 -1.2258898
[5,] 0.8720306  0.8290786

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Julian