从嵌套列表中的所有矩阵中提取相同的列

extract the same column from all matrices in a nested list

关于这个问题有很多条目,但 none 已经解决了我的问题。我需要提取嵌套列表中所有矩阵的第一列。

dput(dlist4)
list(A = list(a = structure(1:4, dim = c(2L, 2L)), b = structure(2:5, dim = c(2L, 
2L))), G = list(a = structure(10:13, dim = c(2L, 2L)), b = structure(5:8, dim = c(2L, 
2L))), M_1 = list(a = structure(10:13, dim = c(2L, 2L)), b = structure(5:8, dim = c(2L, 
2L))), M_2 = list(a = structure(2:5, dim = c(2L, 2L)), b = structure(5:8, dim = c(2L, 
2L))))

预期输出是向量矩阵列表(2 行 x 1 列)。

dput(dlist5)
list(A = list(a = structure(1:2, dim = 2:1), b = structure(2:3, dim = 2:1)), 
    G = list(a = structure(10:11, dim = 2:1), b = structure(5:6, dim = 2:1)), 
    M_1 = list(a = structure(10:11, dim = 2:1), b = structure(5:6, dim = 2:1)), 
    M_2 = list(a = structure(2:3, dim = 2:1), b = structure(5:6, dim = 2:1)))

我使用了下面的代码但得到了同样的错误:Error in x[, 1] : incorrect number of dimensions

tapply(dlist4 ,names(dlist4 ), FUN=function(x) x[,1])

dlist4  %>% map(., ~{.x[,1]})

lapply(dlist4, function(x) x[,1])

rapply(dlist4, function(x) x[,1]) 破坏了我的结构

 A.a1   A.a2   A.b1   A.b2   G.a1   G.a2   G.b1   G.b2 M_1.a1 M_1.a2 
     1      2      2      3     10     11      5      6     10     11 
M_1.b1 M_1.b2 M_2.a1 M_2.a2 M_2.b1 M_2.b2 
 5      6      2      3      5      6 

rapplyhow='list' 结合使用。在我们需要 drop=FALSE 的函数中,否则 one-column 矩阵的维数会自动删除,换句话说,会强制转换为向量。

rapply(dlist4, \(x) x[, 1, drop=FALSE], how='list')
# $A
# $A$a
# [,1]
# [1,]    1
# [2,]    2
# 
# $A$b
# [,1]
# [1,]    2
# [2,]    3
# 
# 
# $G
# $G$a
# [,1]
# [1,]   10
# [2,]   11
# 
# $G$b
# [,1]
# [1,]    5
# [2,]    6
# 
# 
# $M_1
# $M_1$a
# [,1]
# [1,]   10
# [2,]   11
# 
# $M_1$b
# [,1]
# [1,]    5
# [2,]    6
# 
# 
# $M_2
# $M_2$a
# [,1]
# [1,]    2
# [2,]    3
# 
# $M_2$b
# [,1]
# [1,]    5
# [2,]    6

通过 purrr::map_depth()

的另一个选项
library(purrr)  
library(dplyr)
df %>% 
  map_depth(2, ~ .x[,1] %>% as.matrix())

输出:

$A
$A$a
     [,1]
[1,]    1
[2,]    2

$A$b
     [,1]
[1,]    2
[2,]    3
...