如何获得估计密度的函数?

时间:2014-03-18 10:27:19

标签: r function

如何将密度(数据集)的结果保存为函数? 那么,如果我想在该函数中评估点x,它会从该密度(数据集)中获得概率吗?

2 个答案:

答案 0 :(得分:2)

(特定点的密度值不是该点的概率。)

> d <- density(sample(10,1000000,replace=TRUE,prob=(1:10)/sum(1:10)))
> plot(d)

# the density is estimated at a specified number of points. I find the closest to
# the point I want to know the density's value of and then get that value.

> fd <- function(x) d$y[which.min(abs(d$x - x))]
> fd(6)
[1] 0.311895

enter image description here

答案 1 :(得分:2)

如下所示,density函数返回包含密度函数xy值的列表,该列表可用于创建&#34;插值&#34;函数使用approxfun函数。

d <- density(rnorm(100))

str(d)
## List of 7
##  $ x        : num [1:512] -3.85 -3.83 -3.82 -3.8 -3.79 ...
##  $ y        : num [1:512] 0.000135 0.000154 0.000176 0.0002 0.000227 ...
##  $ bw       : num 0.332
##  $ n        : int 100
##  $ call     : language density.default(x = rnorm(100))
##  $ data.name: chr "rnorm(100)"
##  $ has.na   : logi FALSE
##  - attr(*, "class")= chr "density"


pdf <- approxfun(d)


pdf(2)
## [1] 0.05439069

approxfun给出线性近似值

要验证我们可以绘制原始密度d

plot(d)

enter image description here

现在让我们使用我们创建的新函数pdf绘制插值值

x <- seq(-2,2,by=0.01)

points(x, pdf(x))

enter image description here