[R] how to get the rows that satisfy a specific condition

Jim Lemon jim at bitwrit.com.au
Sat Sep 27 12:23:00 CEST 2014


On Fri, 26 Sep 2014 10:15:14 PM Fix Ace wrote:
> Hello, there,
> I wonder if there is an easier way that I would only get the rows that
> satisfies some condition. For example:I have the following matrix, and I
> would like to output only the 3rd row and 4th row, since only these two
> rows contain the numbers greater than 11
> > a
> 
>      [,1] [,2] [,3] [,4] [,5]
> [1,]    1    5    9   13   17
> [2,]    2    6   10   14   18
> [3,]    3    7   11   15   19
> [4,]    4    8   12   16   20
> 
> > a>11
> 
>       [,1]  [,2]  [,3] [,4] [,5]
> [1,] FALSE FALSE FALSE TRUE TRUE
> [2,] FALSE FALSE FALSE TRUE TRUE
> [3,] FALSE FALSE FALSE TRUE TRUE
> [4,] FALSE FALSE  TRUE TRUE TRUE
> I have tried to use a[a>11, ] and it did not work.
> Thanks a lot for the help:)

Hi Fix Ace,
I have to admit that I am unfamiliar with the system of arithmetic that 
you are employing in the above example. In no system with which I am 
conversant are 13, 17, 14 and 18 less than or equal to 11. I can only 
offer the desperate conjecture that you want the third to fifth columns of 
the matrix rather than the third and fourth rows. If this wild surmise 
happens to be the case, I suggest that you try this:

testmat[,apply(testmat,2,function(x) return(max(x) > 11))]

Jim



More information about the R-help mailing list