简体   繁体   English

将函数应用于矩阵上行的成对组合

[英]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). 因此,我有一个矩阵,该矩阵具有四行和x列数(这并不重要)。 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. 我想对不同行的所有可能的成对组合应用一个函数,即遍历“行1-行2”,“行1-行3”等所有6个可能组合并计算一个值的函数。

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: 正如@Imo指出的那样, combn是解决此类问题的方法:

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 . 在这里,我们只是在myMat创建行数的所有2种方式组合。 combn can accept a function, so using your function test , we simply apply test to each combination. combn可以接受一个函数,因此使用您的function test ,我们只需将test应用于每个组合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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