[R] Mode in case of discrete or categorial data

Liaw, Andy andy_liaw at merck.com
Fri Nov 12 16:20:54 CET 2004


You might want to do a bit to handle NAs, as table() excludes them by
default.  Also, you could write it a bit cleaner as:

Mode <- function(x) {
    tab <- table(x)
    m <- names(tab)[tab == max(tab)]
    if (is.numeric(x)) m <- as.numeric(m)
    m
}

(Generally I try avoiding constructs like:
   if (cond) var <- alt1 else var <- alt2
especially when alt1 and alt2 are very similar.  If you need to make changes
later, it's easy to change one and forget the other, etc.  I believe Martin
also made this point in his talk at useR! 2004.)

HTH,
Andy

> From: Vito Ricci
> 
> Thanking John for his suggestion I build this function
> which get the mode of both categorial and discrete
> data.
> 
> 
> Mode<-function(x){t<-table(x)
> if (is.numeric(x)) as.numeric(names(t)[t == max(t)])
> else (names(t)[t == max(t)])
> }
> 
> Any other improvement and suggestion will welcome.
> 
> Best
> 
> Vito
> 
> > s
>  [1] 1 1 6 1 1 7 6 5 6 2 1 4 5 6 6 7 3 5 4 1 7 3 7 3 3
> 7 7 2 1 4 4 2 7 7 6 6 1 2
> [39] 5 1 7 7 5 5 7 3 5 6 5 6 3 6 6 4 2 1 5 3 3 3 6 5 2
> 4 3 2 2 1 5 3 4 3 1 3 3
> > Mode(s)
> [1] 3
> > ss
>  [1] "C" "A" "C" "D" "B" "A" "B" "B" "B" "A" "D" "D"
> "A" "D" "D" "A" "D" "C" "B"
> [20] "D" "C" "B" "D" "C" "B" "C" "D" "A" "C" "A" "A"
> "A" "C" "A" "D" "A" "B" "B"
> [39] "A" "B"
> > Mode(ss)
> [1] "A"
> 
> 
> =====
> Diventare costruttori di soluzioni
> Became solutions' constructors
> 
> "The business of the statistician is to catalyze 
> the scientific learning process."  
> George E. P. Box
> 
> 
> Visitate il portale http://www.modugno.it/
> e in particolare la sezione su Palese 
> http://www.modugno.it/archivio/cat_palese.shtm> l
> 
> 
> ______________________________________________
> 
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! 
> http://www.R-project.org/posting-guide.html
> 
>




More information about the R-help mailing list