Ku-trala
Ku-trala

Reputation: 651

Conditional deleting rows in a matrix

I have a matrix with 3 columns. The 1. column has either the value 1 or 0 in the rows. I want to delete all the rows in the matrix, where the 1. column is equal to zero (or keep the rows containing ones).

Thanks.

Upvotes: 1

Views: 6865

Answers (2)

zx8754
zx8754

Reputation: 56054

Try this:

#dummy matrix
x <- matrix(rep(c(1,0,1),4),ncol=3)

x
#       [,1] [,2] [,3]
# [1,]    1    0    1
# [2,]    0    1    1
# [3,]    1    1    0
# [4,]    1    0    1

#keep rows where 1st column equals to 1
x[x[,1] == 1,]
#       [,1] [,2] [,3]
# [1,]    1    0    1
# [3,]    1    1    0
# [4,]    1    0    1

Upvotes: 1

Miquel
Miquel

Reputation: 15675

So, say that you have this matrix:

A= matrix(c(1, 2, 3, 0, 3, 5, 1, 3, 8),3,3, byrow=T)

The following command will give you a vector of TRUE/FALSE for each row, depending on whether the 1st column is 1 or not:

A[,1]==1

You can then select only those rows like this:

FILTERED = A[A[,1]==1,]

And you'll then find what you ask for in FILTERED

Upvotes: 2

Related Questions