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