如何获得stats :: density中特定值的密度估计?

时间:2014-12-01 13:03:26

标签: r density-plot

假设我有以下数据:

val <- .65
set.seed(1)
distr <- replicate(1000, jitter(.5, amount = .2))
d <- density(distr)

由于stats::density使用特定的bw,因此它不包含区间中的所有可能值(因为它们是无限的):

d$x[ d$x > .64 & d$x < .66 ]

[1] 0.6400439 0.6411318 0.6422197 0.6433076 0.6443955 0.6454834 0.6465713 0.6476592 0.6487471
[10] 0.6498350 0.6509229 0.6520108 0.6530987 0.6541866 0.6552745 0.6563624 0.6574503 0.6585382
[19] 0.6596261

我想找到一种方法来为密度函数提供val,这样它就会返回d$y估计值(然后我会用它来着色密度图的区域)。 / p>

我无法猜出这个问题有多愚蠢,但我无法找到快速解决方案。

我想通过线性插值来获得它,d$y对应于d$x的两个更接近val的值。有更快的方法吗?

1 个答案:

答案 0 :(得分:1)

这说明了使用approxfun

> Af <- approxfun(d$x, d$y)
> Af(val)
[1] 2.348879
> plot(d(
+ 
> plot(d)
> points(val,Af(val) )
> png();plot(d); points(val,Af(val) ); dev.off()

enter image description here