I have a list of matrices of identical dimension. Across all matrices most values are zero.
Those values non-zero vary according to the position of the matrix in the list, and the values for replacement are stored in vectors of the same length as the list of matrices.
What I thus did is to replace the non-zero values by using for loops. However, being relatively new to R I have come to understand that this may not be the most efficient way of doing this, in particular as I have lots of matrices and quite a few non-zero probabilities (and all of this is actually inside some function).
Background is a home-grown Markov model which for now I want to have full control of what's going on (i.e. not using any packages), and the matrices are actually age- and state dependent transition matrices.
So the question: Is there a way to replace the for loops, e.g. by apply? I have tried several hours and searched the forum but can't seem to find a solution for this specific situation. Thanks for your help!
Minimal working example:
# some large matrix
m0 <- list(as.matrix(cbind(matrix(rep(0,3600), nrow=60))))
# replicate to get a list of 10 matrices of identical dimension
m <- rep(m0, 10)
# some fake data for replacement
set.seed(123)
p1 <- abs(rnorm(length(m), 0.1, 0.4))
p2 <- abs(rnorm(length(m), 0.2, 0.3))
p3 <- abs(rnorm(length(m), 0.3, 0.2))
p4 <- abs(rnorm(length(m), 0.4, 0.1))
# some replacements as example
# works with for loops, but is there a more efficient way to replace, e.g., by apply fcts?
for (i in 1:length(m)) {m[[i]][1,1] <- p1[i]}
for (i in 1:length(m)) {m[[i]][2,4] <- p2[i]}
for (i in 1:length(m)) {m[[i]][20,55] <- p3[i]}
for (i in 1:length(m)) {m[[i]][21,55] <- p4[i]}