Ashley
Ashley

Reputation: 69

How to combine matrices in lists of a list in R?

I'm trying to combine the matrices with the same name in lists of a list. For simplicity, I use a list with two lists as an example.

A = matrix(c(1,2,3,4),2)
B = matrix(c(1,2,3,4,5,6),2)
list1 = list(A=A,B=B) 

A = matrix(c(1,2,2,1,1,1),3)
B = matrix(c(1,2,3,3,2,2,1,1,1),3)
list2 = list(A=A,B=B) 

mylist=list(list1,list2)
mylist
[[1]]
[[1]]$A
     [,1] [,2]
[1,]    1    3
[2,]    2    4

[[1]]$B
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6


[[2]]
[[2]]$A
     [,1] [,2]
[1,]    1    1
[2,]    2    1
[3,]    2    1

[[2]]$B
     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    2    2    1
[3,]    3    2    1

I'm hoping to combine all A matrices by row and also combine all B matrices by row. Please note that I have a bunch of lists like list1 and list2 in fact so I prefer to use some loop style operation to this end.

I have tried to simply combine all lists (i.e. list1 and list2 in the example) but I still couldn't combine the separate lists.

> do.call(c, mylist)
$A
     [,1] [,2]
[1,]    1    3
[2,]    2    4

$B
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

$A
     [,1] [,2]
[1,]    1    1
[2,]    2    1
[3,]    2    1

$B
     [,1] [,2] [,3]
[1,]    1    3    1
[2,]    2    2    1
[3,]    3    2    1

Thanks!

Upvotes: 1

Views: 531

Answers (2)

akrun
akrun

Reputation: 886938

Here is an option with tidyverse

library(purrr)
library(dplyr)
mylist %>% 
   transpose %>%
   map(reduce, rbind)
#$A
#     [,1] [,2]
#[1,]    1    3
#[2,]    2    4
#[3,]    1    1
#[4,]    2    1
#[5,]    2    1

#$B
#     [,1] [,2] [,3]
#[1,]    1    3    5
#[2,]    2    4    6
#[3,]    1    3    1
#[4,]    2    2    1
#[5,]    3    2    1

Upvotes: 0

G. Grothendieck
G. Grothendieck

Reputation: 269371

Use mapply with rbind like this:

do.call(mapply, c("rbind", mylist))

giving:

$A
     [,1] [,2]
[1,]    1    3
[2,]    2    4
[3,]    1    1
[4,]    2    1
[5,]    2    1

$B
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
[3,]    1    3    1
[4,]    2    2    1
[5,]    3    2    1

Upvotes: 5

Related Questions