在[R]中计算标称和连续变量的模式

Mar*_*kus 3 r

谁能帮我这个?

如果我跑:

> mode(iris$Species)
[1] "numeric"
> mode(iris$Sepal.Width)
[1] "numeric"
Run Code Online (Sandbox Code Playgroud)

然后我得到"numeric"答案

干杯

中号

Rei*_*son 9

该函数mode()用于找出对象的存储模式,在这种情况下存储为模式"numeric".此函数不用于查找数据集中最"频繁"的观察值,即它不用于查找统计模式.有关?mode此函数在R中的作用以及它对您的问题没有用处的原因,请参阅参考资料.

对于离散数据,模式是集合中最常见的观察值:

> 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
Run Code Online (Sandbox Code Playgroud)

对于连续数据,模式是概率密度函数(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
Run Code Online (Sandbox Code Playgroud)

有关详情?density,请参阅.默认情况下,density()评估n = 512等间隔位置的内核密度估计值.如果这对您来说太粗糙,请增加评估和返回的位置数量:

> sepalwd2 <- with(iris, density(Sepal.Width, n = 2048))
> with(sepalwd, x[which.max(y)])
[1] 3.000314
Run Code Online (Sandbox Code Playgroud)

在这种情况下,它不会改变结果.

  • 请记住,`which.max`只返回具有最大值的第一个索引.比较:`x <-c(1,2,2,1); which.max(x);其中(x == max(x))` (4认同)