如何将矩阵除以行的总和,它有零

时间:2022-07-28 22:30:05

I am pretty new to R and I have a loop which gives sometimes a matrix like this:

我对R很新,我有一个循环,它有时会产生这样的矩阵:

        1 2
  FALSE 0 0
  TRUE  0 2

I need to do as follows: If the two cells in a single row have zeros replace them by 0.5 If one of the cells is not zero divide by the sum of the row

我需要做如下:如果单行中的两个单元格有零,则将它们替换为0.5如果其中一个单元格不是零除以行的总和

so the result of this will be:

所以结果将是:

         1    2
  FALSE 0.5 0.5
  TRUE  0    1

Any idea please? Thank you

有什么想法吗?谢谢

3 个解决方案

#1


1  

If your matrix is x,

如果你的矩阵是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

This will work for a matrix (2 dimensional array) of arbitrary size

这适用于任意大小的矩阵(二维数组)

@akrun's suggested edit, constructing zero_rows with rowSums(x != 0) instead of apply(x, 1, function(r) 0 %in% r) should make this even more efficient.

@ akrun的建议编辑,用rowSums(x!= 0)构造zero_rows而不是apply(x,1,函数(r)0%在%r)应该使这更有效。

#2


1  

Let x <- matrix(c(0, 0, 0, 2), 2))

设x < - 矩阵(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

#3


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

#1


1  

If your matrix is x,

如果你的矩阵是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

This will work for a matrix (2 dimensional array) of arbitrary size

这适用于任意大小的矩阵(二维数组)

@akrun's suggested edit, constructing zero_rows with rowSums(x != 0) instead of apply(x, 1, function(r) 0 %in% r) should make this even more efficient.

@ akrun的建议编辑,用rowSums(x!= 0)构造zero_rows而不是apply(x,1,函数(r)0%在%r)应该使这更有效。

#2


1  

Let x <- matrix(c(0, 0, 0, 2), 2))

设x < - 矩阵(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

#3


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