[R] Finding Values that Occur Most Often in a Vector

hpages at fhcrc.org hpages at fhcrc.org
Thu Jul 10 08:39:04 CEST 2008


Hi Gundala,

This would be a way to do it:

   names(which.max(table(myvector)))

For example:

   > set.seed(99)
   > y <- sample(letters[1:3], 40, replace=TRUE)
    [1] "b" "a" "c" "c" "b" "c" "c" "a" "b" "a" "b" "b" "a" "b" "c" "b"
   [17] "b" "a" "a" "a" "a" "a" "c" "b" "c" "b" "a" "c" "a" "a" "b" "a"
   [33] "b" "b" "a" "b" "c" "c" "b" "c"
   > table(y)
   y
    a  b  c
   14 15 11
   > names(which.max(table(y)))
   [1] "b"

In the case of your 'myvector', you would need to coerce the result
to "numeric". This could be achieved in a more programmatic way with:

   mostrepeated <- function(x) as(names(which.max(table(x))), mode(x))
   mostrepeated(myvector)

Cheers,
H.


Quoting Gundala Viswanath <gundalav at gmail.com>:

> Hi,
>
> Is there a way to do it?
>
> For example I have the following vector:
>
>> print(myvector)
>> [1] -295.8045 -295.8045 -295.8045 -295.8045 -325.4754 -295.8045 -295.8045
>  [8] -295.8045 -413.2099 -295.8045
>
> I want it to return -295.8045, which occur most often.
>
> - Gundala Viswanath
> Jakarta - Indonesia
>
> ______________________________________________
> R-help at r-project.org 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