根据我以前的问题Substract negative matrix element row wise from diagonal in R,我搜索了一种向对角线添加负面元素的方法:
我现在搜索一种方法,将所有负元素(对角线除外)设置为0,并在所有值(diag除外)大于/等于0的条件下从整行中减去它们的值。
行的总和应该是0.
p <- matrix(c(-0.3,0.2,0.2,-0.1, 0.1,-0.4,0.4,-0.1, 0.2,-0.1,-0.4,0.3, -0.1,0.2,0.1,-0.2), ncol = 4, byrow = TRUE)
> p
[,1] [,2] [,3] [,4]
[1,] -0.3 0.2 0.2 -0.1
[2,] 0.1 -0.4 0.4 -0.1
[3,] 0.2 -0.1 -0.4 0.3
[4,] -0.1 0.2 0.1 -0.2
这应该产生如下矩阵:
> p.result
[,1] [,2] [,3] [,4]
[1,] -0.333 0.167 0.167 0.000
[2,] 0.067 -0.433 0.367 0.000
[3,] 0.167 0.000 -0.433 0.267
[4,] 0.000 0.167 0.067 -0.233
答案 0 :(得分:3)
#matrix of indicators, TRUE = off-diagonal negatives
ind <- row(p) != col(p) & p < 0
#vector of values to subtract from each row normalised to make sure row sums are still 1
subs <- rowSums(replace(p, !ind, 0))/rowSums(!ind)
p <- t(t(p) + subs)
p[ind] <- 0
p
[,1] [,2] [,3] [,4]
[1,] -0.33333333 0.1666667 0.16666667 0.0000000
[2,] 0.06666667 -0.4333333 0.36666667 0.0000000
[3,] 0.16666667 0.0000000 -0.43333333 0.2666667
[4,] 0.00000000 0.1666667 0.06666667 -0.2333333
您可以根据需要对新矩阵中的条目进行舍入。