简体   繁体   English

结果列表的成对矩阵

[英]Pairwise matrix to list of outcomes

Suppose we have a matrix M假设我们有一个矩阵M

M       <- matrix(c(1:9),3,3)
diag(M) <- NA
M
     [,1] [,2] [,3]
[1,]   NA    4    7
[2,]    2   NA    8
[3,]    3    6   NA

where each entry describes the outcomes of pairwise interactions.其中每个条目都描述了成对交互的结果。 Each interaction of row i with column j is interepreted as "object i outperformed object j X times".i行与第j列的每次交互都被解释为“对象i优于 object j X 次”。 Examples: Object 2 performs better than object 1 in 2 cases.示例:Object 2 在 2 种情况下表现优于 object 1。 Object 1 performs better than object 3 in 7 cases. Object 1 在 7 个案例中表现优于 object 3。

Is there a quick way to transform this matrix into an object holding this information in a format where each row fully describes the interactions between two objects?有没有一种快速的方法可以将此矩阵转换为 object 以每行都完整描述两个对象之间的交互的格式保存此信息? The goal is something like this:目标是这样的:

     [,1]   [,2]   [,3] [,4]
[1,] "OBJ1" "OBJ2" "N1" "N2"
[2,] "1"    "2"    "4"  "2" 
[3,] "1"    "3"    "7"  "3" 
[4,] "2"    "3"    "8"  "6" 

where the first two columns give the objects that are compared while columns 3 and 4 describe how often OBJ1 outperformed OBJ2 and vice versa.其中前两列给出了比较的对象,而第 3 列和第 4 列描述了OBJ1优于OBJ2的频率,反之亦然。 The interpretation of the first row is: Object 1 has outperformed Object 2 4 times, whereas Object 2 has outperformed Object 1 2 times.第一行的解释是:Object 1 跑赢了 Object 2 4 次,而 Object 2 跑赢了 Object 1 2 次。 I have been playing around with reshape2 and aggregating without useful results so far.到目前为止,我一直在玩reshape2和聚合,但没有得到有用的结果。

Maybe you can try the code below也许你可以试试下面的代码

inds <- t(combn(dim(M)[1], 2))
Mout <- `colnames<-`(
    cbind(inds, M[inds], M[inds[, 2:1]]),
    do.call(paste0, rev(expand.grid(1:2, c("Obj", "N"))))
)

which gives这使

> Mout
     Obj1 Obj2 N1 N2
[1,]    1    2  4  2
[2,]    1    3  7  3
[3,]    2    3  8  6

Another solution could be:另一种解决方案可能是:

M       <- matrix(c(1:9),3,3)
diag(M) <- NA
M1 <- M

M[upper.tri(M, diag=TRUE)] <- NA
M1[lower.tri(M1, diag=TRUE)] <- NA

R1 = reshape2::melt(M1, na.rm=TRUE, value.name="N1")
R2 = reshape2::melt(M, na.rm=TRUE, value.name="N2")

R1$N2 <- R2$N2
rownames(R1) <- NULL

Output: Output:

> R1
  Var1 Var2 N1 N2
1    1    2  4  2
2    1    3  7  3
3    2    3  8  6

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

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