shearer
shearer

Reputation: 94

Substract negative matrix element row wise from diagonal in R

I have an example matrix:

p <- matrix(c(0.5, 0.3, 0.3, -0.1, 0.6, 0.7, -0.2, -0.1), ncol = 4, byrow = T)

> p
     [,1] [,2] [,3] [,4]
[1,]  0.5  0.3  0.3 -0.1
[2,]  0.6  0.7 -0.2 -0.1

with one or more negative elements in every row. The largest element is on the diagonal. I want to create a function, which substracts row wise the negative values from the diagonal and then sets these elements to zero, so that the row sum is again 1.

I tried it myself with the apply function but had no luck until now. Hope someone could help me.

Best Wishes shearer

Upvotes: 2

Views: 91

Answers (1)

Matthew Plourde
Matthew Plourde

Reputation: 44614

Here's one way:

negs <- p < 0
diag(p) <- diag(p) + rowSums(replace(p, ! negs, 0))
p[negs] <- 0
#      [,1] [,2] [,3] [,4]
# [1,]  0.4  0.3  0.3    0
# [2,]  0.6  0.4  0.0    0

Upvotes: 4

Related Questions