Can anyone help me with this?
If I run:
> mode(iris$Species)
[1] "numeric"
> mode(iris$Sepal.Width)
[1] "numeric"
然后我得到了"numeric"
作为答案。
干杯
M
Can anyone help me with this?
If I run:
> mode(iris$Species)
[1] "numeric"
> mode(iris$Sepal.Width)
[1] "numeric"
然后我得到了"numeric"
作为答案。
干杯
M
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
中的最大值。
请参阅 R 的入门手册和帮助文件 ?which
、?max
。
查看 ?mode :mode 可以提供存储模式。
如果您想知道连续随机变量的模式,我最近发布了 ModEstM 包。除了 Gavin Simpson 提出的方法外,它还处理了多峰变量的情况。 例如,如果您研究样本:
> x2 <- c(rbeta(1000, 23, 4), rbeta(1000, 4, 16))
这很明显是双峰的,你得到了答案:
> ModEstM::ModEstM(x2)
[[1]]
[1] 0.8634313 0.1752347
which.max
只返回具有最大值的第一个索引。比较:x<-c(1,2,2,1);which.max(x);which(x==max(x))
。 - Sacha Epskamp