【发布时间】:2014-03-18 10:27:19
【问题描述】:
如何将密度(数据集)的结果保存为函数? 那么,如果我想评估该函数中的点 x,它会给我来自该密度(数据集)的概率?
【问题讨论】:
如何将密度(数据集)的结果保存为函数? 那么,如果我想评估该函数中的点 x,它会给我来自该密度(数据集)的概率?
【问题讨论】:
如下所示,density 函数返回一个包含 x 和 y 密度函数值的列表,可用于使用 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)
现在让我们使用我们创建的新函数pdf 绘制插值
x <- seq(-2,2,by=0.01)
points(x, pdf(x))
【讨论】:
(特定点的密度值不是该点的概率。)
> 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
【讨论】: