[R] "mode" function
David Winsemius
dwinsemius at comcast.net
Wed Sep 1 04:42:14 CEST 2010
On Aug 31, 2010, at 5:19 PM, Iain Martyn wrote:
>
> Hi, I have what I think is a simple question/issue but I have unable
> to find the answer for it either in the R-manual or by browsing the
> web.
>
>
>
> I would like to know if there is a "mode" function in R, such that
> from a vector or matrix the function returns the most common value.
> In other programs I use (such as Matlab) I can have for exampe a 3X3
> matrix A, A=[1 2 3; 1 3 2; 3 3 2] and I can find the mode of the
> rows so that mode(A[1:3,:]) returns a 1X3 matrix [1 3 2].
Matlab must use row major order? Otherwise you statement doesn't make
sense. (You are going to need to adjust to R's default column major
order, if that's the case.)
>
>
>
> Is this possible in R as well? If not, how would one go about this?
Have you considered using names(), which.max() and table()?
A=matrix(c(1, 2, 3, 1, 3, 2, 3, 3, 2), 3 ,3, byrow=TRUE)
apply(A, 2, function(x) names(which.max(table(x)) ))
# [1] "1" "3" "2"
You cannot use just which.max(table(.)) since that would return the
counts. If you want the number, then you need to wrap as.numeric
around the whole mess.
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list