How to obtain the density estimation of a specific value in stats::density?

157 views Asked by At

Suppose I have data like the following:

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

Since stats::density uses a specific bw, it does not include all possible values in the interval (becuase they're infinite):

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

I would like to find a way to provide val to the density function, so that it will return its d$y estimate (I will then use it to color areas of the density plot).

I can't guess how silly this question is, but I can't find a fast solution.

I thought of obtaining it by a linear interpolation of the d$y corresponding to the two values of d$x that are closer to val. Is there a faster way?

1

There are 1 answers

2
IRTFM On BEST ANSWER

This illustrates the use of 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