Reputation: 159
So I have a matrix with four rows and with x number of columns (it doesn't really matter). I want to apply a function to all the possible pairwise combinations of the different rows, i.e. a function that goes over all 6 possible combinations of "row1 - row2", "row1 - row3", etc and computes a value.
Imagine that the matrix looks something like this:
[,1] [,2] [,3] [,4]
0.6923077 1.0000000 0.6153846 1.0000000
1.0000000 0.9444444 0.5833333 0.7142857
1.0000000 1.0000000 1.0000000 1.0000000
1.0000000 0.9090909 0.0000000 0.0000000
For further clarification, the function looks like this:
2*matrix[1,1]*(1-matrix[2,1])+2*matrix[2,1]*(1-matrix[1,1])
As an example, the comparison between the first and the second row would be:
2*0.6923077*(1-1.0000000)+2*1.0000000*(1-0.6923077)
for the first position. Then I would need to compute the same value for all the other columns and, in the end, calculate the mean. I have created a function that is able to do this when the input is two vectors (considering that the row of a matrix, by itself, is just a vector):
test <- function(row1, row2) {
HB <- 2*row1*(1-row2)+2*row2*(1-row1)
return(mean(HB))
}
But I'm not sure how to expand the function or apply it to work on all the possible pairwise comparisons on a matrix. So, any help would be greatly appreciated!
Upvotes: 1
Views: 1039
Reputation: 7597
As @Imo points out, combn
is the way to go for such problems:
combn(nrow(myMat), 2, function(x) test(myMat[x[1], ], myMat[x[2],]))
[1] 0.5648657 0.3461539 1.0069930 0.3789683 0.7169913 1.0454546
Data:
txt <- "0.6923077 1.0000000 0.6153846 1.0000000
1.0000000 0.9444444 0.5833333 0.7142857
1.0000000 1.0000000 1.0000000 1.0000000
1.0000000 0.9090909 0.0000000 0.0000000"
myMat <- as.matrix(read.table(text = txt))
This is what is actually going on:
combn(nrow(myMat), 2)
[,1] [,2] [,3] [,4] [,5] [,6]
[1,] 1 1 1 2 2 3
[2,] 2 3 4 3 4 4
Here we are simply creating all 2 way combinations of the number of rows inmyMat
. combn
can accept a function, so using your function test
, we simply apply test to each combination.
Upvotes: 3