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

标签 r list matrix nested

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

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,否则单列矩阵的维数会自动删除,换句话说,会强制转换为向量。

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

关于r - 从嵌套列表中的所有矩阵中提取相同的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72326431/

相关文章:

r - 使自定义函数可通过管道传输

javascript - 从列表中获取包含 JavaScript 中的 Unicode 的字符串

java - 将具有列表作为属性的 Java 对象写入和读取到 CSV

c# - 列表替换所有以前的元素

c++ - 尝试将矩阵与常量重载运算符相乘两次?

arrays - 如何在 Smalltalk 中访问二维数组中的元素

r - 使用 plotly 和 Shiny 服务器复制图例条目

r - Bootstrap 标准错误位于引导类中的什么位置?

matlab - 计算最常见的值

r - 如何在 R 中使用分类数据制作 3D 图?