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){

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
and should have the name of the associated element of the vector

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