gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 04:29:23 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com