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
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
On Fri, 12 Nov 2004, Vito Ricci wrote:
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.
which.max is design for finding the maximum, so
names(t)[which.max(t)]
-thomas
Dear Thomas,
I believe that which.max() will report only the first maximum in case of
ties [which is why I suggested the more awkward t == max(t)].
Regards,
John
John Fox
Department of Sociology
McMaster University
Hamilton, Ontario
Canada L8S 4M4
From: Thomas Lumley
On Fri, 12 Nov 2004, Vito Ricci wrote:
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.
which.max is design for finding the maximum, so