Search code examples
rlistmatrixlapplymatrix-multiplication

Use lapply to multiply two lists of matrices in R


I have two lists, each one with many matrices. For brevity, here is an example with two matrices per list:

l1 <- list(matrix(1:20, nrow=2),
           matrix(21:40, nrow=2))

l2 <- list(matrix(41:60, nrow=2),
           matrix(61:80, nrow=2))

I am trying to use lapply to (a) remove the first column of each matrix and then (b) multiply each matrix in l1 against the corresponding matrix in l2.

First, I tried:

result <- lapply(l1, function(x,y){
  
  tmp <- x[,-1]*y[,-1]
  return(tmp)
  
}, y=l2)

It didn't work. The problem is that I can't remove the first column from l2 this way. If l2 were a vector instead of a list, the code would work with tmp <- x[,-1]*y[-1]. But even when I try to simply multiply the matrices in each list, it still does not work:

result <- lapply(l1, function(x,y){
  
  tmp <- x*y
  return(tmp)
  
}, y=l2)

Any ideas?


Solution

  • In lapply, you can iterate over only one object. You may use Map here -

    Map(function(x, y)  x[,-1]*y[,-1], l1, l2)
    
    #[[1]]
    #     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
    #[1,]  129  225  329  441  561  689  825  969 1121
    #[2,]  176  276  384  500  624  756  896 1044 1200
    
    #[[2]]
    #     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
    #[1,] 1449 1625 1809 2001 2201 2409 2625 2849 3081
    #[2,] 1536 1716 1904 2100 2304 2516 2736 2964 3200
    

    To use lapply you may use the index to subset both l1 and l2.

    lapply(seq_along(l1), function(x) l1[[x]][, -1] * l2[[x]][, -1])