【问题标题】:How to dynamically list matrices as elements in a list in R [duplicate]如何在R中动态地将矩阵列为列表中的元素[重复]
【发布时间】:2020-11-23 17:29:30
【问题描述】:

这篇文章和我的其他post类似

假设我有 4 个矩阵:

x1 <- matrix(1:9, nrow = 3)
x2 <- matrix(2:10, nrow = 3)
x3 <- matrix(3:11, nrow = 3)
x4 <- matrix(4:12, nrow = 3)

我想以这样的方式将它们放入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    5    8
[2,]    3    6    9
[3,]    4    7   10


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


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

鉴于我有这个list() 来定义x 中的哪个元素在list 中的每个元素中列出:

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

[[1]]
[1] 1 2

[[2]]
[1] 3

[[3]]
[1] 4

有没有办法以更动态的方式编写此列表?目前,我正在使用这个

x <- list(list(x1,x2),list(x3),list(x4))

我尝试使用以下代码,但它们不起作用:

for(p in 1:3) {
  x <- lapply(list, function(l) list(get(paste0("x",list[[p]]))))
}

和

for(p in 1:3) {
  x <- lapply(list, function(l) list(get(paste0("x",l))))
}

【问题讨论】:

    标签: r list matrix lapply


    【解决方案1】:

    你太复杂了,不需要for循环和lapply循环,后者足以得到结果。
    另外,我已将索引向量 list 的名称更改为 ilist,因为 list 已经是基本 R 函数。

    ilist <- list(c(1,2),3,4)
    
    mat <- ls(pattern = "x\\d+$", envir = .GlobalEnv)
    x <- lapply(ilist, function(i) mget(mat[i], envir = .GlobalEnv))
    

    输出是命名成员的列表,名称是mat 中的字符串"x*"。要获得未命名列表的列表,

    x <- lapply(ilist, function(i) unname(mget(mat[i], envir = .GlobalEnv)))
    

    【讨论】:

      猜你喜欢
      • 2015-06-16
      • 2018-02-23
      • 2019-08-09
      • 2019-07-19
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-07
      相关资源
      最近更新 更多