I'm trying to manipulate an R list of lists which themselves contain matrices. What I want to do is similar to this question where a list of matrices, l, is combined into a single matrix using either do.call(rbind, l)
or the rbind.fill.matrix(l)
function from plyr
. However, I want to combine the matrices from across the different elements of the top level list while retaining groupings at the lower level to end up with a list of matrices with the separate elements corresponding to the groupings of the lower level lists.
As an example consider the top level list toplist constructed from three lower level lists:
lowerlist1 = list(matrix1_1, matrix1_2, matrix1_3, matrix1_4)
lowerlist2 = list(matrix2_1, matrix2_2, matrix2_3, matrix2_4)
lowerlist3 = list(matrix3_1, matrix3_2, matrix3_3, matrix3_4)
toplist = list(lowerlist1, lowerlist2, lowerlist3)
where the matrices all have the same number of columns but may have different number of rows. In the end I would like a new list newtoplist with the following structure
newmatrix1 = rbind(matrix1_1, matrix2_1, matrix3_1)
newmatrix2 = rbind(matrix1_2, matrix2_2, matrix3_2)
newmatrix3 = rbind(matrix1_3, matrix2_3, matrix3_3)
newmatrix4 = rbind(matrix1_4, matrix2_4, matrix3_4)
newtoplist = list(newmatrix1, newmatrix2, newmatrix3, newmatrix4)
So a complete example would be:
matrix1_1 = matrix(1.1, 4, 5)
matrix1_2 = matrix(1.2, 3, 5)
matrix1_3 = matrix(1.3, 2, 5)
matrix1_4 = matrix(1.4, 3, 5)
matrix2_1 = matrix(2.1, 2, 5)
matrix2_2 = matrix(2.2, 4, 5)
matrix2_3 = matrix(2.3, 5, 5)
matrix2_4 = matrix(2.4, 2, 5)
matrix3_1 = matrix(3.1, 2, 5)
matrix3_2 = matrix(3.2, 4, 5)
matrix3_3 = matrix(3.3, 5, 5)
matrix3_4 = matrix(3.4, 2, 5)
lowerlist1 = list(matrix1_1, matrix1_2, matrix1_3, matrix1_4)
lowerlist2 = list(matrix2_1, matrix2_2, matrix2_3, matrix2_4)
lowerlist3 = list(matrix3_1, matrix3_2, matrix3_3, matrix3_4)
toplist = list(lowerlist1, lowerlist2, lowerlist3)
newmatrix1 = rbind(matrix1_1, matrix2_1, matrix3_1)
newmatrix2 = rbind(matrix1_2, matrix2_2, matrix3_2)
newmatrix3 = rbind(matrix1_3, matrix2_3, matrix3_3)
newmatrix4 = rbind(matrix1_4, matrix2_4, matrix3_4)
newtoplist = list(newmatrix1, newmatrix2, newmatrix3, newmatrix4)
Can this be done generally?