Home > front end >  Using rbind on matrices in nested lists?
Using rbind on matrices in nested lists?

Time:09-24

I am working in R, and I have a dataset that is a list of lists of matrices. Each sublist in the mainlist has two matrices of equal dimension (10 rows x 2 cols). I would like to rbind() each list of matrices into a single matrix (20 rows x 2 cols). But I do not want to combine every sublist into a single big matrix. Gonna try my best to write a sample code for it but the real data is pretty complex so I'll do my best.

> matrix_1 <- matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), nrow = 5, ncol = 2, byrow = TRUE)
> matrix_2 <- matrix(c(9, 8, 7, 6, 5, 4, 3, 2, 1), nrow = 5, ncol = 2, byrow = TRUE)
> matrix_3 <- matrix(c(101, 91, 81, 71, 61, 51, 41, 31, 21, 11), nrow = 5, ncol = 2, byrow = TRUE)
> matrix_4 <- matrix(c(22, 20, 19, 18, 17, 16, 15, 14, 13, 12), nrow = 5, ncol = 2, byrow = TRUE)

> sublist_1 <- list(matrix_1, matrix_2)
[[1]]
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    1    3
[4,]    7    4
[5,]    8    3

[[2]]
     [,1] [,2]
[1,]   10    9
[2,]    8    7
[3,]    6    5
[4,]    4    3
[5,]    2    1

> sublist_2 <- list(matrix_3, matrix_4)
[[1]]
     [,1] [,2]
[1,]  101   91
[2,]   81   71
[3,]   61   51
[4,]   41   31
[5,]   21   11

[[2]]
     [,1] [,2]
[1,]   22   20
[2,]   19   18
[3,]   17   16
[4,]   15   14
[5,]   13   12

> mainlist <- list(sublist_1, sublist_2)

What I really want is to make this:

> rbind(sublist_1[[1]], sublist_1[[2]])
      [,1] [,2]
 [1,]    1    5
 [2,]    2    6
 [3,]    1    3
 [4,]    7    4
 [5,]    8    3
 [6,]   10    9
 [7,]    8    7
 [8,]    6    5
 [9,]    4    3
[10,]    2    1

apply to all of the sublists in the mainlist.

I've tried to use various combinations of lapply, mapply, map, do.call, etc. to make it work, but either I don't know the right combinations or I need something else.

I've also noticed that rbind(sublist_1) does not work, which is making it difficult to use lapply. It has to be written as rbind(sublist_1[[1]], sublist_1[[2]]).

Thank you very much for your help.

CodePudding user response:

Loop over the outer list, convert the inner list elements to data.frame and use do.call with rbind

out <- lapply(mainlist, function(x)  do.call(rbind, lapply(x, as.data.frame)))
  • Related