Get strings that do not contain 0

I would like to create a new matrix from another matrix, but only with rows that do not contain 0, how can I do this?

+4
source share
4 answers

I found that this can be done very simply

x <- matrix(c(0,0,0,1,1,0,1,1,1,1), ncol = 2, byrow = TRUE) y <- cbind (x[which(x[,1]*x[,2] >0), 1:2]) 
+1
source

Here is a more vector way.

 x <- matrix(c(0,0,0,1,1,0,1,1,1,1), ncol = 2, byrow = TRUE) x[rowSums(x==0)==0,] 
+6
source

I only collect the great offers that others have already given. I like the ability to store this as a function and generalize values ​​except 1, including categorical values ​​(also selects positively or negatively with the select argument):

 v.omit <- function(dataframe, v = 0, select = "neg") { switch(select, neg = dataframe[apply(dataframe, 1, function(y) !any(y %in% (v))), ], pos = dataframe[apply(dataframe, 1, function(y) any(y %in% (v))), ]) } 

Give it a try.

 x <- matrix(c(0,0,0,1,1,0,1,1,1,1,NA,1), ncol = 2, byrow = TRUE) v.omit(x) v.omit(mtcars, 0) v.omit(mtcars, 1) v.omit(CO2, "chilled") v.omit(mtcars, c(4,3)) v.omit(CO2, c('Quebec', 'chilled')) v.omit(x, select="pos") v.omit(CO2, c('Quebec', 'chilled'), select="pos") v.omit(x, NA) v.omit(x, c(0, NA)) 

Please do not mark my answer as correct, as others answered in front of me, this is just to expand the conversation. Thanks for the code and the question.

+1
source

I am sure there are better ways, but here is one approach. We will use the apply() and all() functions to create a Boolean vector for indexing into the matrix of interest.

 x <- matrix(c(0,0,0,1,1,0,1,1,1,1), ncol = 2, byrow = TRUE) x > x [,1] [,2] [1,] 0 0 [2,] 0 1 [3,] 1 0 [4,] 1 1 [5,] 1 1 > x[apply(x, 1, function(y) all(y > 0)) ,] [,1] [,2] [1,] 1 1 [2,] 1 1 
0
source

Source: https://habr.com/ru/post/1379044/


All Articles