Home > OS >  Storing matrices in a list from a nested loop
Storing matrices in a list from a nested loop

Time:08-17

for (i in seq(-1, 1, by = 0.01))
  for (j in seq(2, 6, by = 1)) {
    M <- matrix(i, ncol = j, nrow = j)
    diag(M) <- 1
    print(M) 
  }

I get the results I want in M.

My problem is - I want to store the results (as in M) in a list of matrices in which each matrix has a single identifier consisting of the correlation (from -1 to 1 in steps of 0.01) and its dimensions from (here) 2x2 to 6x6 so I can call it later.

Any ideas? Thank you.

CodePudding user response:

Here is a for loop way.

inx <- seq(-1, 1, by = 0.01)
jnx <- 2:6
id <- expand.grid(inx, jnx)
M_list <- vector("list", length = nrow(id))
names(M_list) <- apply(id, 1, \(x) sprintf("%0.2f_%d", x[1], x[2]))

k <- 0L
for (j in seq(2, 6, by = 1))
  for (i in seq(-1, 1, by = 0.01)) {
    M <- matrix(i, ncol = j, nrow = j)
    diag(M) <- 1
    #print(M) 
    k <- k   1L
    M_list[[k]] <- M
  }
length(M_list)
#> [1] 1005
head(names(M_list))
#> [1] "-1.00_2" "-0.99_2" "-0.98_2" "-0.97_2" "-0.96_2" "-0.95_2"

Created on 2022-08-17 by the reprex package (v2.0.1)

And a lapply loop one.

inx <- seq(-1, 1, by = 0.01)
jnx <- 2:6

M_list2 <- lapply(jnx, \(j) {
  lapply(inx, \(i){
    M <- matrix(i, ncol = j, nrow = j)
    diag(M) <- 1
    M
  })
})

M_list2 <- unlist(M_list2, recursive = FALSE)
names(M_list2) <- apply(expand.grid(inx, jnx), 1, \(x) sprintf("%0.2f_%d", x[1], x[2]))
length(M_list2)
#> [1] 1005
head(names(M_list2))
#> [1] "-1.00_2" "-0.99_2" "-0.98_2" "-0.97_2" "-0.96_2" "-0.95_2"

Created on 2022-08-17 by the reprex package (v2.0.1)


And access the correlation/dimension by name:

M_list[["-1.00_2"]]
#>      [,1] [,2]
#> [1,]    1   -1
#> [2,]   -1    1
M_list[["-0.99_2"]]
#>       [,1]  [,2]
#> [1,]  1.00 -0.99
#> [2,] -0.99  1.00
M_list[["0.25_4"]]
#>      [,1] [,2] [,3] [,4]
#> [1,] 1.00 0.25 0.25 0.25
#> [2,] 0.25 1.00 0.25 0.25
#> [3,] 0.25 0.25 1.00 0.25
#> [4,] 0.25 0.25 0.25 1.00

M_list2[["-0.05_2"]]
#>       [,1]  [,2]
#> [1,]  1.00 -0.05
#> [2,] -0.05  1.00
M_list2[["0.10_3"]]
#>      [,1] [,2] [,3]
#> [1,]  1.0  0.1  0.1
#> [2,]  0.1  1.0  0.1
#> [3,]  0.1  0.1  1.0
M_list2[["0.25_4"]]
#>      [,1] [,2] [,3] [,4]
#> [1,] 1.00 0.25 0.25 0.25
#> [2,] 0.25 1.00 0.25 0.25
#> [3,] 0.25 0.25 1.00 0.25
#> [4,] 0.25 0.25 0.25 1.00

Created on 2022-08-17 by the reprex package (v2.0.1)

  • Related