[R] Counting elements in 2 rows of a matrix

Jan de Leeuw deleeuw at stat.ucla.edu
Sat Aug 31 08:19:01 CEST 2002


 > x
      [,1] [,2] [,3] [,4] [,5]
[1,]    1    0    1    0    0
[2,]    0    1    0    1    0
[3,]    1    0    1    0    0
[4,]    1    1    1    0    1
 > table(x[1,],x[2,])

     0 1
   0 1 2
   1 2 0
 > as.vector(table(x[1,],x[2,]))
[1] 1 2 2 0
 >prs<-function(x,i,j) as.vector(table(x[i,],x[j,])[2:4])
 > prs(x,1,2)
[1] 2 2 0
 > prs(x,1,3)
[1] 0 0 2

or use

ab.common<-function(x) crossprod(t(x))
ab.unique<-function(x) outer(rowSums(x),rep(1,nrow(x)))-pr11(x)

The first function will give what two rows have in common, the
second will give what they have unique (01 below the
diagonal, 10 above)

 > ab.common(x)
      [,1] [,2] [,3] [,4]
[1,]    2    0    2    2
[2,]    0    2    0    1
[3,]    2    0    2    2
[4,]    2    1    2    4
 > ab.unique(x)
      [,1] [,2] [,3] [,4]
[1,]    0    2    0    0
[2,]    2    0    2    1
[3,]    0    2    0    0
[4,]    2    3    2    0

For ab.unique you can also use
ab.unique <-function(x) matrix(rowSums(x), nrow(x),nrow(x))-ab.common(x)
which may be marginally faster.

On Friday, August 30, 2002, at 10:22 PM, Fredy Mejía wrote:

> Dear R-users:
>
> Sorry to bother so late with this question, which surely has simple  
> answer.  I'm working with matrices that contain either "1" or "0", for  
> example:
>
>   [,1] [,2] [,3] [,4] [,5]
> A    1    0    1    0    0
> B    0    1    0    1    0
> C    1    0    1    0    0
> D    1    1    1    0    1
>
> I want to count the number of "1" common to, say, A and B, the number  
> of "1" that appear only in A and the number of "1" that appear only in  
> B.  Please let me know if there's a simple way of doing this without  
> the complicated for...next loops that have come across my mind.
>
> Fredy Mejía
===
Jan de Leeuw; Professor and Chair, UCLA Department of Statistics;
US mail: 9432 Boelter Hall, Box 951554, Los Angeles, CA 90095-1554
phone (310)-825-9550;  fax (310)-206-5658;  email: deleeuw at stat.ucla.edu
homepage: http://gifi.stat.ucla.edu
   
------------------------------------------------------------------------ 
-------------------------
           No matter where you go, there you are. --- Buckaroo Banzai
                    http://gifi.stat.ucla.edu/sounds/nomatter.au
   
------------------------------------------------------------------------ 
-------------------------

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list