[R] The most common row in a matrix?

Peter Dalgaard p.dalgaard at biostat.ku.dk
Mon Nov 20 14:01:52 CET 2006


Atte Tenkanen <attenka at utu.fi> writes:

> Hi Gabor,
> 
> Your version works with the small sample matrix but I didn't get it to work with a larger 675x8 -matrix. I don't know why. I don't know the command aggregate if there is something.
> I got this one from Peter Alspach
> 
> which.max(table(paste(data.frame(t(MATRIX)), sep=',')))
> 
> and it seems to work as well as one posted by Dimitrios Rizopoulos.

Or, basically the same idea:

count <- table(apply(MATRIX, 1, paste, collapse=" "))
count[which.max(count)]

Notice that similar code is already used in unique.matrix and
unique.data.frame. Methods based on aggregate() may be inefficient,
since it is implemented as a wrapper for tapply(), which means that a
rather large intermediate table is generated. (This could very likely
be improved upon.)

> Atte
> 
> > Try this:
> > 
> > a <- matrix(1:3, 4, 5)
> > 
> > a.ag <- aggregate(1:nrow(a), as.data.frame(a), length)
> > a.ag[which.max(a.ag$x), 1:ncol(a)]
> > 
> > 
> > On 11/19/06, kone <attenka at utu.fi> wrote:
> > > Hi,
> > >
> > > How do you get the most common row from a matrix? If I have a matrix
> > > like this
> > >
> > > array(1:3,dim=c(4,5))
> > >
> > >      [,1] [,2] [,3] [,4] [,5]
> > > [1,]    1    2    3    1    2
> > > [2,]    2    3    1    2    3
> > > [3,]    3    1    2    3    1
> > > [4,]    1    2    3    1    2
> > >
> > > in which rows 1 and 4 are similar, I want to find that vector c
> > > (1,2,3,1,2).
> > >
> > > Atte Tenkanen
> > > University of Turku, Finland


-- 
   O__  ---- Peter Dalgaard             Øster Farimagsgade 5, Entr.B
  c/ /'_ --- Dept. of Biostatistics     PO Box 2099, 1014 Cph. K
 (*) \(*) -- University of Copenhagen   Denmark          Ph:  (+45) 35327918
~~~~~~~~~~ - (p.dalgaard at biostat.ku.dk)                  FAX: (+45) 35327907



More information about the R-help mailing list