There are many entries on this problem but none has solved mine. I need to extract the first column of all the matrices in a nested list.
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))))
The expected output is a list of vector matrices (2 rows x 1 column).
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)))
I used the codes below but got the same error: 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])
broke my structure
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
CodePudding user response:
Using rapply
with how='list'
. In the function we need drop=FALSE
, otherwise the dimensions of one-column matrices automatically get dropped, in other words coerced to a vector.
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