矩阵中的二元最大值

时间:2014-03-21 13:37:13

标签: r matrix

想象一下你有矩阵mat

mat <- matrix(c(0,2,3,3,0,1,1,1,0), nrow = 3,byrow=TRUE)
rownames(mat) <- list("a","b","c")
colnames(mat) <- list("a","b","c")
mat
#  a b c
#a 0 2 3
#b 3 0 1
#c 1 1 0

我想找到哪个上三角和下三角对最大。例如b:a >a:b a:c > c:a而非mat

然后我想返回一个mtrix,其中对中具有最大值的单元格获得1,而其他更小的值,并且关系变为零。 result <- matrix(c(0,0,1,1,0,0,0,0,0), nrow = 3,byrow=TRUE) rownames(result ) <- list("a","b","c") colnames(result ) <- list("a","b","c") result # a b c #a 0 0 1 #b 1 0 0 #c 0 0 0 的结果是:

{{1}}

1 个答案:

答案 0 :(得分:1)

试试这个:

> (mat > t(mat)) + 0
  a b c
a 0 0 1
b 1 0 0
c 0 0 0

为领带返回0.5:

> (mat > t(mat)) + .5 * (mat == t(mat))
    a   b   c
a 0.5 0.0 1.0
b 1.0 0.5 0.5
c 0.0 0.5 0.5