[R] extracting the mode of a vector

John Wilkinson wilks at dial.pipex.com
Mon Apr 23 18:48:40 CEST 2007



Beno?t L?t? wrote:
> Hello,
>
> I have an elementary question (for which I couldn't find the answer on the
> web or the help): how can I extract the mode (modal score) of a vector?

Assuming that your vector contains only integers:

 > v <- sample(1:5, size=20, replace=T)
 > v
  [1] 1 1 1 1 2 3 5 1 1 5 2 4 1 3 1 1 5 4 1 5
 > vt <- table(v)
 > as.numeric(names(vt[vt == max(vt)]))
[1] 1
 >

Cheers,
Gad

#----------------------------
or more succinctly,

> names(vt[which.max(vt)])
[1] "1"

John



More information about the R-help mailing list