LoginSignup
13
11

More than 5 years have passed since last update.

Rで最頻値を求める

Posted at

Rにはなぜか最頻値を求める関数って無いですよね。。。

statmode.R
statmode <- function(x) {
  names(which.max(table(x)))
}
実行例
x <- c("a", "b", "b", "c", "c", "c", "d", "d", "e")
y <- c(1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 5, 5)
z <- c(1.1, 1.1, 2.2, 2.3, 2.4, 3.1, 3.2, 3.4, 3.5, 4.8, 4.8, 4.8, 5.6, 5.6)
(mode <- statmode(x))
(mode <- statmode(y))
(mode <- statmode(z))
結果
[1] "c"
[1] "3"
[1] "4.8"

他にいいやりかたがあったら教えてください。

13
11
4

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
11