I want to reorganize the grand list of dlist4
in such a way that all the a
's stay in one nested list and all the b
's in another nested list.
A = list(a = matrix(1:4, 2), b = matrix(2:5, 2))
G = list(a = matrix(10:13, 2), b = matrix(5:8, 2))
M_1 = list(a = matrix(10:13, 2), b = matrix(5:8, 2))
M_2 = list(a = matrix(2:5, 2), b = matrix(5:8, 2))
dlist4 <- tibble::lst(A, G, M_1, M_2)
The answers from these questions: R list - combine elements with same name and combine elements of list of lists with the same name got me close. I need the list structure to I removed the unlist()
, but this result is unexpected.
tapply(dlist4,names(dlist4), FUN=function(x) unname(x))
$A
$A$a
[,1] [,2]
[1,] 1 3
[2,] 2 4
$A$b
[,1] [,2]
[1,] 2 4
[2,] 3 5
$G
$G$a
[,1] [,2]
[1,] 10 12
[2,] 11 13
$G$b
[,1] [,2]
[1,] 5 7
[2,] 6 8
$M_1
$M_1$a
[,1] [,2]
[1,] 10 12
[2,] 11 13
$M_1$b
[,1] [,2]
[1,] 5 7
[2,] 6 8
$M_2
$M_2$a
[,1] [,2]
[1,] 2 4
[2,] 3 5
$M_2$b
[,1] [,2]
[1,] 5 7
[2,] 6 8
I need a list of a
that has four elements, a$A
, a$G
, a$M_1
, and a$M_2
, and the same with a list of b
; and then a
and b
nested in a bigger list. Thanks so much for any hints.
CodePudding user response:
do.call(rlist::list.zip, dlist4)
or
purrr::lift(rlist::list.zip)(dlist4)
?
$a
$a$A
[,1] [,2]
[1,] 1 3
[2,] 2 4
$a$G
[,1] [,2]
[1,] 10 12
[2,] 11 13
$a$M_1
[,1] [,2]
[1,] 10 12
[2,] 11 13
$a$M_2
[,1] [,2]
[1,] 2 4
[2,] 3 5
$b
$b$A
[,1] [,2]
[1,] 2 4
[2,] 3 5
$b$G
[,1] [,2]
[1,] 5 7
[2,] 6 8
$b$M_1
[,1] [,2]
[1,] 5 7
[2,] 6 8
$b$M_2
[,1] [,2]
[1,] 5 7
[2,] 6 8