[R] delete rows whose sum is X

Sarah Goslee sarah.goslee at gmail.com
Fri Mar 4 15:30:28 CET 2011


On Fri, Mar 4, 2011 at 8:50 AM, purna <mijony at live.se> wrote:
> Rnoob here.
> I have a matrix of zeroes ond ones. I want to delete the rows whose sum of
> values is not =5, alternatively extract the rows who sum up to 5.
>
> Thank you/Mikael

I think you would greatly benefit from reading some of the intro to R
materials that are widely available.

> mymat <- matrix(sample(c(1,0), 100, r=TRUE), ncol=10)
> rowSums(mymat)
 [1] 3 4 3 6 3 4 5 7 7 3
> mymat[rowSums(mymat) == 5, , drop=FALSE]
     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
[1,]    0    0    0    1    1    1    0    0    1     1
> mymat[rowSums(mymat) != 5, , drop=FALSE]
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    0    1    1    0    0    0    0    0    1     0
 [2,]    0    1    0    1    0    0    0    0    1     1
 [3,]    0    0    0    0    1    0    0    1    1     0
 [4,]    0    1    0    1    1    1    1    0    0     1
 [5,]    1    0    1    0    0    1    0    0    0     0
 [6,]    1    1    1    0    0    0    0    1    0     0
 [7,]    1    1    0    1    1    1    1    0    1     0
 [8,]    1    0    1    1    1    1    1    1    0     0
 [9,]    0    0    0    0    0    0    1    0    1     1


Sarah


-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list