[R] counting occurances of matching rows in a matrix

Balazs Torma torma at ilab.sztaki.hu
Fri Jul 13 16:11:39 CEST 2007


I need help regarding to the following problem:

Consider this matrix:

> M <- matrix(c(1,2, 4,3, 1, 2),3, 2, byrow=TRUE)
> M
     [,1] [,2]
[1,]    1    2
[2,]    4    3
[3,]    1    2

I would like to have a matrix which counts the identical rows and places the counts into its third column. I tried with ftable():

> as.data.frame(ftable(M[,1], M[,2]))
  Var1 Var2 Freq
1    1    2    2
2    4    2    0
3    1    3    0
4    4    3    1

This would be exactly what I want without the 0-freq rows. The problem is that ftable() counts the occurances of all possible factor combinations, which is inproper because the real matrix is very long for which I want to count. (I know that I could filter out 0-frequencies afterwards but I would like ftable not to produce 0-frequencies unnecessarily (it would consume too much space)).

I tried table() too, but I couldn't tell it that it should consider each row as one data point, and not all elements in the matrix separately:

> as.data.frame(table(M))
  M Freq
1 1    2
2 2    2
3 3    1
4 4    1

Any help greatly appreciated!
Balazs Torma



More information about the R-help mailing list