Gundala Viswanath
2008-Jul-10 06:04 UTC
[R] Finding Values that Occur Most Often in a Vector
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
hpages at fhcrc.org
2008-Jul-10 06:39 UTC
[R] Finding Values that Occur Most Often in a Vector
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.
>
If you just want the value which is the most frequent try as.numeric(names(which.max(table(c( -295.8045 ,-295.8045, -295.8045, -295.8045 ,-325.4754 ,-295.8045, -295.8045, -295.8045, -413.2099, -295.8045))))) [1] -295.8045 There may be easier ways Regards Duncan Mackay Department of Agronomy and Soil Science University of New England ARMIDALE NSW 2351 Email: home: mackay at northnet.com.au At 16:04 10/07/2008, you wrote:>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.