Search code examples
rlistmatrixapplymatrix-multiplication

Matrix calculation between list objects in R


I have created list of objects in R as follows:

set.seed(1234)
data <- matrix(rnorm(3*4,mean=0,sd=1), 3, 4) 
results <- lapply(1:ncol(data), function(i) outer(data[, i], data[, i]))

all 4 list objects have dim=3x3. I also have the following matrix matr <- matrix(c(2,4,6,8),ncol=4), where each value corresponds to the above list objects.

Then, I use this equation matr[,1]*matr[,2]*results[[1]]*results[[2]] between the first two objects in order to create the below matrix

          [,1]      [,2]       [,3]
[1,] 64.135122 2.6966755 12.4307531
[2,]  2.696676 0.1133865  0.5226732
[3,] 12.430753 0.5226732  2.4093448

How can I calculate the above equation for all all possible object combinations and save them to a new list?


Solution

  • We can use combn to create pairwise combination on the sequence of the list, extract the elements and do the multiplication

    new_lst <- combn(seq_along(results), 2, \(i) matr[,i[1]] * matr[,i[2]] * 
        results[[i[1]]] * results[[i[2]]], simplify = FALSE)
    names(new_lst) <- combn(seq_along(results), 2, paste, collapse="_")
    

    -output

    > new_lst
    $`1_2`
              [,1]      [,2]       [,3]
    [1,] 64.135122 2.6966755 12.4307531
    [2,]  2.696676 0.1133865  0.5226732
    [3,] 12.430753 0.5226732  2.4093448
    
    $`1_3`
              [,1]       [,2]      [,3]
    [1,]  5.775451 -1.2624981 -5.095849
    [2,] -1.262498  0.2759787  1.113939
    [3,] -5.095849  1.1139391  4.496217
    
    $`1_4`
              [,1]      [,2]       [,3]
    [1,]  18.46710 -2.275650 -18.610758
    [2,]  -2.27565  0.280422   2.293352
    [3,] -18.61076  2.293352  18.755530
    
    $`2_3`
              [,1]      [,2]      [,3]
    [1,] 43.621251 -7.589849 -9.242303
    [2,] -7.589849  1.320590  1.608108
    [3,] -9.242303  1.608108  1.958223
    
    $`2_4`
              [,1]       [,2]       [,3]
    [1,] 139.47970 -13.680683 -33.754187
    [2,] -13.68068   1.341852   3.310735
    [3,] -33.75419   3.310735   8.168537
    
    $`3_4`
              [,1]     [,2]      [,3]
    [1,] 12.560327 6.404863 13.837154
    [2,]  6.404863 3.266019  7.055953
    [3,] 13.837154 7.055953 15.243778