R - multiple nested loops inferno -


i want create list of matrices 3 vectors, sd_vec strictly positive:

z_vec <- c(qnorm(0.90), qnorm(0.95), qnorm(0.975))  # 95% ci, 90% ci, 80% ci me_vec <- c(0.50, 0.25, 0.10, 0.05) sd_vec <- rnorm(n = 9, 0.8, 0.4) sd_vec[which(sd_vec <= 0)] <- 0.1 

my question two-fold:

  • how can generalize loops 1 matrix multiple matrices? can create matrices stepwise (2 levels of nesting), indexing breaks down when nest 3 levels.
  • how can avoid for-loops altogether (in spirit of this answer)? welcome answers sapply(), etc.

here example of attempt:

new_n <- matrix(na, 3,4) for(i in seq_along(z_vec)){   for(j in seq_along(me_vec)){     new_n[i, j] <- ((z_vec[i] * sd_vec[1]) /me_vec[j])^2   } }  new_n #      [,1]  [,2]  [,3] [,4] # [1,] 2.45  9.82  61.4  245 # [2,] 4.04 16.17 101.1  404 # [3,] 5.74 22.96 143.5  574 

then indexing failure:

new_n <- vector("list", length = length(sd_vec)) for(k in seq_along(sd_vec)){   for(i in seq_along(z_vec)){     for(j in seq_along(me_vec)){       new_n[[k]][i, j] <- ((z_vec[i] * sd_vec[k]) /me_vec[j])^2     }   } } 

with error message error in new_n[[k]][i, j] <- ((z_vec[i] * sd_vec[k])/me_vec[j])^2 : incorrect number of subscripts on matrix

thanks , assistance trivial question!

concerning error message in last example, think due incorrect initialization of list of matrices. might try replace

new_n <- vector("list", length = length(sd_vec)) 

with

new_n <- replicate(length(sd_vec), matrix(na, 3, 4), simplify = false) 

this should resolve indexing error problem. finding elegant , compact way rewrite complex nested loops issue. trust community come nice solutions.

update

the nested loops in first example can rewritten this:

new_n <- t(sapply(seq_along(z_vec), function(x,y) ((z_vec[x] * sd_vec[1]) / me_vec[y])^2)) 

Comments

Popular posts from this blog

c# - Better 64-bit byte array hash -

webrtc - Which ICE candidate am I using and why? -

php - Zend Framework / Skeleton-Application / Composer install issue -