简体   繁体   中英

store results of for loop in R in matrix

I have three loops, and I need to store the output from the 2nd loop, 2 25x1 vectors called too_store and ordinary_store, for each of the 5 iterations of the outermost loop (h in pi). I have made empty matrices [ordinaryMatx and tooMatx] that are 25x5 and I would like to store them there. Any advice on how to rewrite the last two lines to accomplish this? The loop is running but the data for the matrices is NA at the end.

mu = c( 0, 0, 0 )
phi = c( -0.2, 1.9 )
beta = c( -0.4, 0.8 )

pi=seq(-0.5,0.5,0.25)
l=length(pi)


R=500

m = 25
ntest = 10 * ( 1:1:m )


ordinary_store = rep( NA, m )
too_store = rep( NA, m )
ordinary_store1 = rep( NA, R )
too_store1 = rep( NA, R )
ordinaryMatx=matrix(data=NA,nrow=m,ncol=l)
tooMatx=matrix(data=NA,nrow=m,ncol=l)

for (h in pi){
  
  Sigma = matrix( c( 2,h, 0,
                     h, 2, 0,
                     0, 0, 2), nrow=3, ncol=3 )
  
  for (i in 1:m){
     set.seed(6633421)  
    
    n=ntest[i]
    
    for (r in 1:R) {
   
      res = mvrnorm(n, mu, Sigma)
      s = res[,1] 
      q = res[,2]
      
      Z = res[,3]
      Z = cbind( rep(1, n), Z )
      
      X = cbind( rep(1,n), Z %*% phi + q )
      
      Y = X %*% beta + s
      beta_ordinary = solve( t(X) %*% X) %*% t(X) %*% Y

      Pz = Z %*% solve( t(Z) %*% Z ) %*% t(Z) 
      beta_too = solve( t(X) %*% Pz %*% X ) %*% t(X) %*% Pz %*% Y 

      ordinary_store1[r] = beta_ordinary[2]
      too_store1[r] = beta_too[2] 
    }
    average_ordinary = mean(ordinary_store1)
    average_too = mean(too_store1)
 
    ordinary_store[i] = average_ordinary
    too_store[i] = average_too
  }
  ordinaryMatx[,h]=ordinary_store
  tooMatx[,h]=too_store
}

If you have defined a variable such as a matrix / table outside a for-loop and want to assign values to it inside the for-loop, use the global assignement operater:

.... loop
 m[i] <<- value
....

Then you won`t get NAs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM