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:
[[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)
#[[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
推荐阅读
- java - 单击图片时,它应该存储在我手机的内部存储器中
- c# - 使用 linq 从使用 c# 的数据表中获取总和和不同的列数据
- three.js - three.js 如何为背景使用渐变色
- c - 无法复制文本文件并将其粘贴到新文件 C
- javascript - 停止在 javascript 中向父级传播事件
- javascript - 在 JQuery 中加载动态级联下拉列表?
- angular - 如何在Angular2中进行计算?
- hmatrix - windows 10下haskell hmatrix安装
- kotlin - 当 kotlin 是一种编译语言时,Kotlin notebook 将如何工作?
- java - 如何计算 S3 文件内容的 SHA-256 校验和