# [R] a more elegant approach to getting the majority level

Wiener, Matthew matthew_wiener at merck.com
Thu May 26 17:15:13 CEST 2005

```The which.max solution is fine as long as the maximum is always unique.
Otherwise, which.max will give you the first maximum.

So using the "x == max(x) " version will have an advantage if there can be
ties.

Regards,

Matt Wiener

-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Uwe Ligges
Sent: Thursday, May 26, 2005 10:57 AM
To: rxg218 at psu.edu
Cc: r-help at stat.math.ethz.ch
Subject: Re: [R] a more elegant approach to getting the majority level

Rajarshi Guha wrote:

> Hi, I have a factor and I would like to find the most frequent level.
>
> I think my current approach is a bit long winded and I was wondering if
> there was a more elegant way to do it:
>
> x <- factor(sample(1:0, 5,replace=TRUE))
>
> levels(x)[ which( as.logical((table(x) == max(table(x)))) == TRUE ) ]

library(fortunes)
fortune("TRUE")

x == max(x) should be replaced by which.max(x)

as.logical() is superfluous

Hence we get:
names(which.max(table(x)))

Uwe Ligges

> (The length of x will always be an odd number, so I wont get a tie in
> max())
>
> Thanks,
>
> -------------------------------------------------------------------
> Rajarshi Guha <rxg218 at psu.edu> <http://jijo.cjb.net>
> GPG Fingerprint: 0CCA 8EE2 2EEB 25E2 AB04 06F7 1BB9 E634 9B87 56EE
> -------------------------------------------------------------------
> Alcohol, an alternative to your self
> - 'Alcohol' by the Bare Naked Ladies
>
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help