jo.H jo.H -4 years ago 101
R Question

Create a new matrix in each for loop iteration

I'd like to use a for loop to create a new matrix in each iteration of the loop.

mining_t = c("Zr_t","Sr_t","Rb_t","Zn_t","Cu_t","Fe_t","Mn_t","V_t","Ti_t","Ca_t","K_t","Ba_t")

for (i in mining_t){
??=matrix(c(VI9A_mn[1:7,i],VI9A_mn[8:14,i],VI9A_mn[15:21,i]),nrow=7,byrow=FALSE)
colnames(i)=c("45","90","135")
}


I'd like each matrix to have 3 columns of 7 rows. Each new matrix is made from the ith column (all rows) of the matrix
VI9A_mn
and should have the name of the associated element of the vector
mining_t
.

Answer Source

We can do a split by column of 'VI9A_mn'

lst <- lapply(split(VI9A_mn, col(VI9A_mn)), 
                matrix, ncol=3, dimnames = list(NULL, c(45, 90, 135)))

It is better to keep the matrix objects in a list. But, if we insist to have multiple objects in global environment, use list2env

list2env(lst, envir = .GlobalEnv)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download