首页 > 解决方案 > R create list of matrices

问题描述

This post is similar to my post earlier.

Let's say if I have the codes below:

my_list <- list(c(1,2),3,4)

x = list()
for(i in 1:4) {
  x[[i]] <- matrix(1:9*i, nrow = 3)
}

Where my_list is:

[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4

What should I write to get the same results as below?

[[1]]
[[1]][[1]]
     [,1] [,2] [,3]
[1,]    1    4    7
[2,]    2    5    8
[3,]    3    6    9

[[1]][[2]]
     [,1] [,2] [,3]
[1,]    2    8   14
[2,]    4   10   16
[3,]    6   12   18


[[2]]
     [,1] [,2] [,3]
[1,]    3   12   21
[2,]    6   15   24
[3,]    9   18   27

[[3]]
     [,1] [,2] [,3]
[1,]    4   16   28
[2,]    8   20   32
[3,]   12   24   36

I have tried using the codes below but it does not work for this case:

mat <- ls(pattern = "x[[\\d+$]]", envir = .GlobalEnv)
mat_list <- lapply(my_list, function(i) mget(mat[i], envir = .GlobalEnv))

and

mat_list <- lapply(my_list, function(i) x[[i]])

标签: rlistmatrixlapply

解决方案


You can use relist to make the structure of x similar to my_list :

relist(x, my_list)

#[[1]]
#[[1]][[1]]
#     [,1] [,2] [,3]
#[1,]    1    4    7
#[2,]    2    5    8
#[3,]    3    6    9

#[[1]][[2]]
#     [,1] [,2] [,3]
#[1,]    2    8   14
#[2,]    4   10   16
#[3,]    6   12   18


#[[2]]
#[[2]][[1]]
#     [,1] [,2] [,3]
#[1,]    3   12   21
#[2,]    6   15   24
#[3,]    9   18   27


#[[3]]
#[[3]][[1]]
#     [,1] [,2] [,3]
#[1,]    4   16   28
#[2,]    8   20   32
#[3,]   12   24   36

Similar output is obtained using lapply :

lapply(my_list, function(i) x[i])

If you want to avoid the nested output for single matrix and want it exactly as shown you can use :

lapply(my_list, function(i) if(length(i) > 1) x[i] else x[[i]])

#[[1]]
#[[1]][[1]]
#     [,1] [,2] [,3]
#[1,]    1    4    7
#[2,]    2    5    8
#[3,]    3    6    9

#[[1]][[2]]
#     [,1] [,2] [,3]
#[1,]    2    8   14
#[2,]    4   10   16
#[3,]    6   12   18


#[[2]]
#     [,1] [,2] [,3]
#[1,]    3   12   21
#[2,]    6   15   24
#[3,]    9   18   27

#[[3]]
#     [,1] [,2] [,3]
#[1,]    4   16   28
#[2,]    8   20   32
#[3,]   12   24   36

You can read the difference between [ and [[ here : The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe


推荐阅读