【发布时间】:2016-07-21 12:50:46
【问题描述】:
给定方阵m如下(nxn):
m <- matrix(1:5,ncol = 5,nrow = 5,byrow = F)
[,1] [,2] [,3] [,4] [,5]
[1,] 1 1 1 1 1
[2,] 2 2 2 2 2
[3,] 3 3 3 3 3
[4,] 4 4 4 4 4
[5,] 5 5 5 5 5
我想分别提取上下三角形的元素并取相对频率。
我们可以通过这样的循环天真地做到这一点(这里是n=5):
for (i in 1:(n-1))
for (j in (i+1):n){
x <- m[i,j]
y <- m[j,i]
m[i,j] <- x/(x+y)
m[j,i] <- y/(x+y)
}
这是所需的输出:
[,1] [,2] [,3] [,4] [,5]
[1,] 1.0000000 0.3333333 0.2500000 0.2000000 0.1666667
[2,] 0.6666667 2.0000000 0.4000000 0.3333333 0.2857143
[3,] 0.7500000 0.6000000 3.0000000 0.4285714 0.3750000
[4,] 0.8000000 0.6666667 0.5714286 4.0000000 0.4444444
[5,] 0.8333333 0.7142857 0.6250000 0.5555556 5.0000000
我们能否更有效地生成此输出?
附言
我知道m[upper.tri(m)] 和m[lower.tri(m)],但这不是诀窍,因为提取元素的顺序不同。例如,m[upper.tri(m)] 会给我:
[1] 1 1 2 1 2 3 1 2 3 4
而我想要的上三角形是:
[1] 1 1 1 1 2 2 2 3 3 4
【问题讨论】:
-
@AlexIoannides 删除的答案提供了线索 -
?upper.tri和?lower.tri构成了解决方案的基础...... -
@BenBolker 我知道,但这不是诀窍。
-
@m0h3n 看看这个帖子github.com/gastonstat/matrixkit/blob/master/R/…
-
你可以通过
t()和upper.tri/lower.tri的适当组合来完成它,我认为...... -
如果你提供一些测试数据,我可以看看。我会尝试
upper.tri(m)/(m+t(m))