[英]How do I divide rows by the row sum and rows that meet a certain condition (row Sum >100)in matrix?r
[英]How to divide a matrix by the sum of rows and it has zeros
我对R很陌生,并且有一个循环,有时会给出如下矩阵:
1 2
FALSE 0 0
TRUE 0 2
我需要执行以下操作:如果单个行中的两个单元格都为零,则将它们替换为0.5如果单元格之一不是零,则除以该行的总和
因此,结果将是:
1 2
FALSE 0.5 0.5
TRUE 0 1
有什么想法吗? 谢谢
如果您的矩阵是x
,
(x <- matrix(c(0, 0, 0, 2), 2))
# [,1] [,2]
# [1,] 0 0
# [2,] 0 2
zero_rows <- as.logical(rowSums(x != 0))
x[zero_rows,] <- x[zero_rows,]/sum(x[zero_rows,])
x[rowSums(x) == 0, ] <- rep(0.5, ncol(x))
x
# [,1] [,2]
# [1,] 0.5 0.5
# [2,] 0.0 1.0
这将适用于任意大小的矩阵(二维数组)
@akrun的建议编辑,使用rowSums(x != 0)
而不是apply(x, 1, function(r) 0 %in% r)
构造zero_rows
应该会更加有效。
令x <- matrix(c(0, 0, 0, 2), 2))
t(apply(x,1,function(y)if(all(!y))replace(y,!y,0.5)else if(any(!y))y/sum(y) else y))
[,1] [,2]
[1,] 0.5 0.5
[2,] 0.0 1.0
x = matrix(c(0, 0, 0, 2), 2)
t(apply(x, 1L, function(y) ifelse(all(y == 0), return(rep(0.5, length(y))), return(y/sum(y)))))
# [,1] [,2]
#[1,] 0.5 0.5
#[2,] 0.0 1.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.