[R] The most common row in a matrix?

Bill.Venables at csiro.au Bill.Venables at csiro.au
Mon Nov 20 03:26:11 CET 2006


 
Here is an idea you can develop as you wish.  You need to be specific
about how to handly several rows that occur equally commonly, for
example.

mcr <- function(x, drop = FALSE) { #'most common row'
  xx <- do.call("paste", c(data.frame(x), sep = "\r"))
  tx <- table(xx)
  mx <- names(tx)[which(tx == max(tx))[1]]
  x[match(mx, xx), , drop = drop]
}

Slightly extend your example:

> x
     [,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
[5,]    1    2    3    1    2
[6,]    2    3    1    2    3
[7,]    3    1    2    3    1
[8,]    1    2    3    1    2

Now:

> mcr(x)
     [,1] [,2] [,3] [,4] [,5]
[1,]    1    2    3    1    2
> mcr(x, drop = T)
[1] 1 2 3 1 2

___

This kind of example suggests that it might be useful to make 'match'
generic (like 'duplicated' and 'unique'), with methods for data frames
and matrices.

Bill Venables.

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of kone
Sent: Monday, 20 November 2006 5:31 AM
To: r-help at stat.math.ethz.ch
Subject: [R] The most common row in a matrix?

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

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide
http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.



More information about the R-help mailing list