简体   繁体   中英

Apply a function over pairwise combinations of rows on a matrix

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, ie 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!

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 in myMat . combn can accept a function, so using your function test , we simply apply test to each combination.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM