[英]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.