TotalNoob
TotalNoob

Reputation: 11

How can I conditionally remove rows of a matrix based on values in those rows?

I want to remove several entire rows of a matrix based on the values in a row. For example, if I have rows

Row 1
Row 2
Row 3
Row 4
Row 5

and row 2 has a 1 in it, I want the output to be:

Row 1
Row 3
Row 4
Row 5

Nothing I've tried works, so any help would be much appreciated.

Upvotes: 1

Views: 104

Answers (4)

ThomasIsCoding
ThomasIsCoding

Reputation: 101373

Some other base R options (borrow mat from @akrun)

> subset(mat, rowSums(mat == 1) == 0)
     [,1] [,2] [,3]
[1,]    5    4    3
[2,]    5    6    7
[3,]    4    6    7

> do.call(rbind, apply(mat, 1, function(x) if (!1 %in% x) x))
     [,1] [,2] [,3]
[1,]    5    4    3
[2,]    5    6    7
[3,]    4    6    7

Upvotes: 1

akrun
akrun

Reputation: 887118

An option with collapse

library(collapse)
sbt(mat, !dapply(mat==1, MARGIN = 1, FUN = any))
     [,1] [,2] [,3]
[1,]    5    4    3
[2,]    5    6    7
[3,]    4    6    7

data

mat <- structure(c(5, 1, 5, 4, 4, 2, 6, 6, 3, 3, 7, 7), .Dim = 4:3)

Upvotes: 1

TarJae
TarJae

Reputation: 78927

Update: See Martin Gal's comment: Replacing any(x == 1) with all(x != 1) could save you an ! in front of condition.

Data from Ronak Shah (many thanks!). We could feed a logical vector with TRUE and FALSE and use it for subsetting:

All 1 will be assigned TRUE within condition -> [1] FALSE TRUE FALSE FALSE

To select all rows that are not 1 use !

condition <- apply (mat, 1, function(x) any(x==1))

mat[!condition,]

output:

> mat[!condition,]
     [,1] [,2] [,3]
[1,]    5    4    3
[2,]    5    6    7
[3,]    4    6    7

Upvotes: 4

Ronak Shah
Ronak Shah

Reputation: 388982

If you have a matrix like this -

mat <- matrix(c(5, 4, 3, 
         1, 2, 3, 
         5, 6, 7, 
         4, 6, 7), byrow = TRUE, 4, 3)

mat

#     [,1] [,2] [,3]
#[1,]    5    4    3
#[2,]    1    2    3
#[3,]    5    6    7
#[4,]    4    6    7

and you want to remove rows which has 1 in any column using rowSums you can do -

result <- mat[rowSums(mat == 1, na.rm = TRUE) == 0, ]
result

#     [,1] [,2] [,3]
#[1,]    5    4    3
#[2,]    5    6    7
#[3,]    4    6    7

Upvotes: 4

Related Questions