I have a vector p and a matrix Z. If values become negative in the first equation below, I would like to multiply them by a scaling factor sf. I have applied this for column 3 now, but my real data is a huge matrix, so how can I write an argument that finds all negative values, calculates sf and then multiplies them by the sf equation for that specific cell?
data:
p <- c(12, 10, 5, 8)
Z <- read.table(header=FALSE,
text=" 0 5 2 3
2 0 2 1
10 3 0 0
1 2 3 0
")
code:
p + colSums(Z)-rowSums(Z) #if negative in this equation, then find scaling factor sf:
sf <- (p[[3]] + colSums(Z[3])) / rowSums(Z[3,]) #scaling factor
(Z[3,]) * sf #multiply the negative value with scaling factor