-1

I would like to iterate through pairwise combinations of elements in a list in R, and then execute a function using the combination as an input.

In this minimal example I (1) define three matrices, (2) combine them into a list containing the matrices as elements, and then (3) would like to calculate the dot product of the combinations of the elements in the list (ie. matrix 1 vs. matrix 2 and matrix 2 vs. matrix 3).

set.seed

m1 = as.matrix(replicate(2, rnorm(2)))
m2 = as.matrix(replicate(2, rnorm(2)))
m3 = as.matrix(replicate(2, rnorm(2)))

matrix.list = list(m1, m2, m3)

dot.prod = function(matrix.x, matrix.y){
    return(matrix.x %*% matrix.y)
}

So far I have the following to have all combinations of matrix.list as inputs for dot.prod() using a nested loop.

for (i in 1:length(matrix.list)){

  for (j in 1:length(matrix.list)){

            print(dot.prod(matrix.list[[i]], matrix.list[[j]]))
  }
}

Is it possible to do this by using a combinatorial function in R (like combn())? I would be very grateful for any suggestions.

Edit: the function itself doesn't matter - I want to know how to use combinations of elements from a list as inputs for any R function

Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
user 123342
  • 463
  • 1
  • 9
  • 21
  • 1
    Could you provide a reproducible example (just add `set.seed` to the top) and the show the desired output for this example? It is not entirely clear to me what structure you want at the end and what structure you are starting with. – lmo Jun 13 '17 at 12:04

1 Answers1

2

Let's just do

oo <- outer(matrix.list, matrix.list, Vectorize(crossprod, SIMPLIFY = FALSE))

which gives you a matrix list. Accessing the result is handy. oo[1,2] (actually get into the list oo[1,2][[1]]) gives the cross product between matrix 1 and matrix 2.

Note, matrix cross product is not %*% (but if you insist, use Vectorize("%*%", SIMPLIFY = FALSE)). As the operation is not symmetric, oo[1,2] is different from oo[2,1].

See How to perform pairwise operation like `%in%` and set operations for a list of vectors for the original idea of this.


Thanks for your response. To clarify: I want to calculate the dot product, not the cross product, as I stated in my initial question. However, the function itself doesn't matter - I want to know how to use combinations of elements from a list as inputs for any R function.

No idea of what you want. Give you a few other options and pick up yourself. They are all different.

This?

combn(matrix.list, 2, function (u) u[[1]] %*% u[[2]])

This?

mapply("%*%", matrix.list[-length(matrix.list)], matrix.list[-1], SIMPLIFY = FALSE)
Zheyuan Li
  • 71,365
  • 17
  • 180
  • 248
  • Thanks for your response. To clarify: I want to calculate the dot product, not the cross product, as I stated in my initial question. However, the function itself doesn't matter - I want to know how to use combinations of elements from a list as inputs for any R function. – user 123342 Jun 13 '17 at 13:49