[英]Calculating the Mode for Nominal as well as Continuous variables in [R]
誰能幫我這個?
如果我跑:
> mode(iris$Species)
[1] "numeric"
> mode(iris$Sepal.Width)
[1] "numeric"
然后我得到"numeric"
作為答案
干杯
米
功能mode()
用於找出對象的存儲模式,在這種情況下,存儲為模式"numeric"
。 此函數不用於查找數據集中最“頻繁”的觀察值,即它不用於查找統計模式。 有關此函數在R中的作用以及它對您的問題沒有用處的原因,請參閱?mode
。
對於離散數據,模式是集合中最常見的觀察值:
> set.seed(1) ## reproducible example
> dat <- sample(1:5, 100, replace = TRUE) ## dummy data
> (tab <- table(dat)) ## tabulate the frequencies
dat
1 2 3 4 5
13 25 19 26 17
> which.max(tab) ## which is the mode?
4
4
> tab[which.max(tab)] ## what is the frequency of the mode?
4
26
對於連續數據,模式是概率密度函數(PDF)達到最大值的數據的值。 由於您的數據通常是來自某些連續概率分布的樣本,我們不知道PDF,但我們可以通過直方圖或通過核密度估計更好地估計它。
返回虹膜數據,這是從連續數據確定模式的示例:
> sepalwd <- with(iris, density(Sepal.Width)) ## kernel density estimate
> plot(sepalwd)
> str(sepalwd)
List of 7
$ x : num [1:512] 1.63 1.64 1.64 1.65 1.65 ...
$ y : num [1:512] 0.000244 0.000283 0.000329 0.000379 0.000436 ...
$ bw : num 0.123
$ n : int 150
$ call : language density.default(x = Sepal.Width)
$ data.name: chr "Sepal.Width"
$ has.na : logi FALSE
- attr(*, "class")= chr "density"
> with(sepalwd, which.max(y)) ## which value has maximal density?
[1] 224
> with(sepalwd, x[which.max(y)]) ## use the above to find the mode
[1] 3.000314
有關詳細信息,請參閱?density
。 默認情況下, density()
評估n = 512
等距位置的核密度估計值。 如果這對您來說太粗糙,請增加評估和返回的位置數量:
> sepalwd2 <- with(iris, density(Sepal.Width, n = 2048))
> with(sepalwd, x[which.max(y)])
[1] 3.000314
在這種情況下,它不會改變結果。
看?mode
: mode
為您提供存儲模式。 如果您想要具有最大計數的值,則使用表。
> Sample <- sample(letters[1:5],50,replace=T)
> tmp <- table(Sample)
> tmp
Sample
a b c d e
9 12 9 7 13
> tmp[which(tmp==max(tmp))]
e
13
如果函數沒有按照您的想法進行操作,請閱讀幫助文件。
一些額外的解釋:
max(tmp)
為最大的tmp
tmp == max(tmp)
給出一個長度為tmp的邏輯向量,指示值是否等於max(tmp)。
which(tmp == max(tmp))
返回向量中值為TRUE
的索引。 這些索引用於選擇tmp中的值,即最大值。
請參閱幫助文件?which
, ?max
和R的介紹手冊。
See?mode:mode 是給你的存儲模式。
如果你想知道連續隨機變量的模式,我最近發布了 package ModEstM 。 除了 Gavin Simpson 提出的方法外,它還解決了多模態變量的情況。 例如,如果您研究樣本:
> x2 <- c(rbeta(1000, 23, 4), rbeta(1000, 4, 16))
這顯然是雙峰的,你會得到答案:
> ModEstM::ModEstM(x2)
[[1]]
[1] 0.8634313 0.1752347
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.