Ender
Ender

Reputation: 307

how to find particular rows or columns in R with specific conditions

For example, if we have a matrix or say array with the following format

M = matrix(c(1,1,0,0,0,1,0,1,0,0,0,0,1,1,0,1), # the data elements 
    nrow=4,              # number of rows 
    ncol=4,              # number of columns 
    byrow = TRUE)        # fill matrix by rows 

How can find the index of which rows and columns only have 0 inside? what if we have a more complicated matrix in which we need to find out in the rows or columns with all the numbers inside are in a specific interval?

M = matrix(c(1,1,12,34,0,19,15,1,0,17,12,0,21,1,11,1), # the data elements 
    nrow=4,              # number of rows 
    ncol=4,              # number of columns 
    byrow = TRUE)        # fill matrix by rows 

How should I find the column in which all the numbers are between (10 - 20)?

Thank you very much for any one who can help on this.

And, also, I can not use for or while loops to deal with it.

Upvotes: 0

Views: 89

Answers (1)

SabDeM
SabDeM

Reputation: 7200

You can do something like that:

 which(apply(M, 1, sum) == 0 )
[1] 3
 which(apply(M, 2, sum) == 0 )
[1] 3

Where with 1 you search for the rows and with 2 columns. The results tell you what row and column has all zeros. With the M you can see that the row number 3 and the column number 3 have only zeros.

Or as suggested by Akrun you can use rowSums and colSums that should be faster.

 which(rowSums(M) == 0)
[1] 3
 which(colSums(M) == 0)
[1] 3

Upvotes: 2

Related Questions