如果矩阵值低于 0,则乘以
if matrix values are below 0, multiply by
我有一个向量 p 和一个矩阵 Z。如果下面第一个等式中的值变为负数,我想将它们乘以比例因子 sf。我现在已经将它应用于第 3 列,但我的实际数据是一个巨大的矩阵,所以我如何编写一个参数来找到所有负值,计算 sf,然后将它们乘以该特定单元格的 sf 方程?
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
我认为这应该可行:
test <- p + colSums(Z) - rowSums(Z)
sf <- (p + colSums(Z)) / rowSums(Z)
multiplier = ifelse(test < 0, sf, 1)
result <- diag(multiplier) %*% as.matrix(Z)
result
# V1 V2 V3 V4
# [1,] 0.000000 5.000000 2 3
# [2,] 2.000000 0.000000 2 1
# [3,] 9.230769 2.769231 0 0
# [4,] 1.000000 2.000000 3 0
如果你的矩阵真的大,上面的行总和和列总和分别计算两次是低效的,我们可以通过保存和重新使用它们来改进它结果:
cs = colSums(Z)
rs = rowSums(Z)
test <- p + cs - rs
sf <- (p + cs) / rs
multiplier = ifelse(test < 0, sf, 1)
result <- diag(multiplier) %*% as.matrix(Z)
我有一个向量 p 和一个矩阵 Z。如果下面第一个等式中的值变为负数,我想将它们乘以比例因子 sf。我现在已经将它应用于第 3 列,但我的实际数据是一个巨大的矩阵,所以我如何编写一个参数来找到所有负值,计算 sf,然后将它们乘以该特定单元格的 sf 方程?
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
我认为这应该可行:
test <- p + colSums(Z) - rowSums(Z)
sf <- (p + colSums(Z)) / rowSums(Z)
multiplier = ifelse(test < 0, sf, 1)
result <- diag(multiplier) %*% as.matrix(Z)
result
# V1 V2 V3 V4
# [1,] 0.000000 5.000000 2 3
# [2,] 2.000000 0.000000 2 1
# [3,] 9.230769 2.769231 0 0
# [4,] 1.000000 2.000000 3 0
如果你的矩阵真的大,上面的行总和和列总和分别计算两次是低效的,我们可以通过保存和重新使用它们来改进它结果:
cs = colSums(Z)
rs = rowSums(Z)
test <- p + cs - rs
sf <- (p + cs) / rs
multiplier = ifelse(test < 0, sf, 1)
result <- diag(multiplier) %*% as.matrix(Z)