Warm tip: This article is reproduced from serverfault.com, please click

Filter Matrix by overlaying boolean mask of same size with same output dimensions in R

发布于 2020-12-04 10:38:22

Given this 5x5 adjacency matrix:

library(matrixcalc)
set.seed(1)
matrix(runif(25, 0, 10), nrow=5, ncol=5) %>% upper.triangle

Resulting in this matrix:

     [,1]     [,2]     [,3]     [,4]     [,5]
[1,] 2.655087 8.983897 2.059746 4.976992 9.347052
[2,] 0.000000 9.446753 1.765568 7.176185 2.121425
[3,] 0.000000 0.000000 6.870228 9.919061 6.516738
[4,] 0.000000 0.000000 0.000000 3.800352 1.255551
[5,] 0.000000 0.000000 0.000000 0.000000 2.672207

I want to filter all entries that are TRUE in this boolean filter mask while keeping the size, filling the FALSE entries with NA or 0.

mask <- matrix(rep(FALSE, 25), nrow=5, ncol=5)
mask[1,2] <- TRUE
mask[2,3] <- TRUE
mask[1,5] <- TRUE 
mask[3,5] <- TRUE

Resulting in this mask:

     [,1]  [,2]  [,3]  [,4]  [,5]
[1,] FALSE  TRUE FALSE FALSE  TRUE
[2,] FALSE FALSE  TRUE FALSE FALSE
[3,] FALSE FALSE FALSE FALSE TRUE
[4,] FALSE FALSE FALSE FALSE FALSE
[5,] FALSE FALSE FALSE FALSE FALSE

To output a matrix of same size filtered by the mask:

    [,1]     [,2]     [,3] [,4]     [,5]
[1,]    0 8.983897 0.000000    0 9.347052
[2,]    0 0.000000 1.765568    0 0.000000
[3,]    0 0.000000 0.000000    0 6.516738
[4,]    0 0.000000 0.000000    0 0.000000
[5,]    0 0.000000 0.000000    0 0.000000
Questioner
user13607508
Viewed
0
Ronak Shah 2020-12-04 18:43:23

If your matrix is called mat you can do :

mat[!mask] <- 0