[R] Mode in case of discrete or categorial data
Prof Brian Ripley
ripley at stats.ox.ac.uk
Fri Nov 12 16:44:03 CET 2004
On Fri, 12 Nov 2004, Liaw, Andy wrote:
> 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.)
Also,
var <- if(cond) alt1 else alt2
is more idiomatic S (and easier to read).
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272866 (PA)
Oxford OX1 3TG, UK Fax: +44 1865 272595
More information about the R-help
mailing list