任何人都可以帮助我吗?计算[R]中名义和连续变量的模式
如果我运行:
> mode(iris$Species)
[1] "numeric"
> mode(iris$Sepal.Width)
[1] "numeric"
然后我得到"numeric"
的答案
干杯
中号
任何人都可以帮助我吗?计算[R]中名义和连续变量的模式
如果我运行:
> mode(iris$Species)
[1] "numeric"
> mode(iris$Sepal.Width)
[1] "numeric"
然后我得到"numeric"
的答案
干杯
中号
看到?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.
介绍手册功能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
对于连续数据,所述模式是在该概率密度函数(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
在这种情况下,它不会改变结果。
对于which.max()函数+1 + – 2011-02-16 12:33:21
这很好。我是R的新手,但想知道你做了什么...你会介意简单地解释一下tmp [哪个(tmp == max(tmp))]部分? – Markus 2011-02-16 12:20:30