Skip to content
Prev 58946 / 398503 Next

Mode in case of discrete or categorial data

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