Search code examples
rlistmatrixpipeline

Multiply all the matrices in a nested list together


I have a list of 4 matrices

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))

dlist <- pmap(list(A, G, M_1, M_2), list) %>% 
  simplify() %>%
  map(.,
    ~{names(.) <-  c("A",
                     "G",
                     "M_1",
                     "M_2"); .}) 

I used the above pipeline instead of dlist <- list(A,G,M_1, M2) because I want to keep the nested lists' names.

I need a list of 4 matrices, each being the product of all the elements within A, G, M_1, M_2. The code below gave me a list of 2, a, and b, in which a is the product of all the matrices named a across all the four lists (A, G, M_1, M_2); and similarly for b.

res <- dlist  %>%
  map(., ~{Reduce( "%*%", .)}) 

res
$a
     [,1]  [,2]
[1,] 5519  9859
[2,] 8220 14684

$b
     [,1]  [,2]
[1,] 5866  7970
[2,] 7773 10561

I don't seem to find anything similar asked before. How do I fix my code? Thanks a lot.


Solution

  • tibble::lst() creates self-named lists (analogous to data.frame).

    map(lst(A, G, M_1, M_2), \(x) x[[1]] %*% x[[2]])
    

    or slightly more inscrutably

    map(lst(A, G, M_1, M_2), lift(`%*%`))
    

    (or, of course)

    lst(A, G, M_1, M_2) %>% map(lift(`%*%`))