RE: [R] Mode in case of discrete or categorial data

2004-11-12 Thread Liaw, Andy
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

RE: [R] Mode in case of discrete or categorial data

2004-11-12 Thread Prof Brian Ripley
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

Re: [R] Mode in case of discrete or categorial data

2004-11-12 Thread 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 names(t)[which.max(t)] -thomas

RE: [R] Mode in case of discrete or categorial data

2004-11-12 Thread John Fox
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

RE: [R] Mode in case of discrete or categorial data

2004-11-12 Thread Liaw, Andy
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