1

I'm running some Monte Carlo simulations of OLS estimation in which I conduct several versions of the same simulation for different beta values. To do this, I have set up a for loop to run the simulation (which has 1000 repetitions), and wrapped a second loop around this in which I want to assign the beta values.

So, I have set up 4 matrices to store the results of each version of the simulation, and I want to identify which matrix to write to using the for loop counter.

Here is a simple example of my setup:

reps = 1000
mat1 = matrix(NA, nrow=reps, ncol=2)
mat2 = matrix(NA, nrow=reps, ncol=2)
mat3 = matrix(NA, nrow=reps, ncol=2)
mat4 = matrix(NA, nrow=reps, ncol=2)

for(i in 1:4){
    #Here I am going to alter my beta values for each iteration of i
    for(j in 1:reps){
        #Here I run my simulation and store values to mat1, mat2, mat3, mat4
        #I want to store to mat1 on first iteration of j, mat2 on second etc.
        model <- lm(Y~X)
        mat[["i"]][j,1] <- model$coef[1]
        mat[["i"]][j,2] <- model$coef[2]
    }
}

For iteration 1 of the i loop I want mat[["i"]][j,1] to associate with column 1 of mat1, iteration 2 to mat2 etc. This does not work obviously as I have it coded here and I cannot figure out how to make it work.

I could accomplish this with if else statements on the value of i, but I'd like to avoid this if possible.

EDIT

Thanks for the help everyone! This worked:

reps = 1000
myMatList <- list()

for(i in 1:4){
    #Here I am going to alter my beta values for each iteration of i

    myMatList[[i]] <- matrix(NA, nrow=reps, ncol=2)

    for(j in 1:reps){
        #Here I run my simulation and store values to mat1, mat2, mat3, mat4
        #I want to store to mat1 on first iteration of j, mat2 on second etc.
        model <- lm(Y~X)
        myMatList[[i]][j,1] <- model$coef[1]
        myMatList[[i]][j,2] <- model$coef[2]
    }
}
dj20b22
  • 65
  • 1
  • 5
  • Store the matrices in a list: `myMatList <- mget(ls(pattern="mat\\d+"))` then reference them. See [this post](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for more details. It discusses data.frames, but the concepts are the same. – lmo Jan 18 '17 at 14:39
  • Does this work for you `do.call(rbind,lapply(1:4000,function(x) { data.frame(iter = x, t(coefficients(lm(Y~ X, data=mtcars)))) }))` – Silence Dogood Jan 18 '17 at 15:35

1 Answers1

0

I am not sure as your code does not work, but I think this might help:

l <- list()
reps = 10

for(i in 1:4) {
  l[[i]] <- matrix(NA, nrow=reps, ncol=2)
}
l[[1]][1, 1] # [1] NA
l[[1]][1, ]
Christoph
  • 6,841
  • 4
  • 37
  • 89