Reputation: 119
I have multiple n*n matrices where each cell either contains values 0 or 1. My goal is to delete all IDs after a certain ID, where rows and columns have only 0's in all matrices of my data set.
Here is some data:
m1 <- matrix(c(1,0,0,1,0,0,0,0,0,0,0,0), 4, 4)
m2 <- matrix(c(1,0,0,1,0,0,0,0,0,0,0,0), 4, 4)
In this example, I would like to check for every ID after 2 if the corresponding row and column shows only 0's for both matrices. Here, this is true for ID 2&3: I then want to delete row & column 3 in all matrices, but keep row & column 2.
As you can imagine, my data set is a lot bigger and this can't be done by hand.
I tried:
m1b <- m1 [which(rowSums(m1[3:4,]) > 0 & colSums(m1[3:4,]) > 0), ]
But this omits the first 2 rows and only checks one matrix. Any help is appreciated.
Upvotes: 0
Views: 88
Reputation: 360
m1[3:4,]
but you apply it on m1
. which(rowSums(m1[3:4,]) > 0)
returns 2 but it is the 4th row of m1
, you need to add 2 to the results of which and tell you want to keep the 2 first rows by concatenate the results with 1 and 2For one matrix, you can do:
m1[c(1, 2, 2 + which(rowSums(m1[3:4,]) > 0)), which(colSums(m1[3:4,]) > 0)]
or
m1[c(rep(TRUE, 2), rowSums(m1[3:4,]) > 0), colSums(m1[3:4,]) > 0]
Now, to get the conditions for multiple matrices, you can use &
between vectors of boolean
columnToKeep <- (colSums(m1[3:4,]) > 0) & (colSums(m2[3:4,]) > 0)
rowToKeep <- (c(rep(TRUE, 2), rowSums(m1[3:4,]) > 0)) & (c(rep(TRUE, 2), rowSums(m2[3:4,]) > 0))
m1[rowToKeep, columnToKeep]
m2[rowToKeep, columnToKeep]
Upvotes: 1