简体   繁体   English

R 创建矩阵列表

[英]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:其中my_list是:

[[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]])

You can use relist to make the structure of x similar to my_list :您可以使用relist使x的结构类似于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 获得类似的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:如果您想避免单个矩阵的嵌套 output 并希望它完全如图所示,您可以使用:

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您可以在此处阅读[[[之间的区别: The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list 或 dataframe

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM