0
# The Old Faithful geyser data
d <- density(faithful$eruptions, bw = "sj")
> head(d$x)
[1] 1.179869 1.188363 1.196857 1.205350 1.213844 1.222338

I'm using density function in {stats}, and I'm wondering if it's possible to see density at specific values in the output? For example, currently, I have density estimates at eruption values of [1] 1.179869 1.188363 ... but what if I want to know the density estimates at eruption values 1 2 5 10 ...? Is there a way to extract these the density object, d?

Adrian
  • 9,229
  • 24
  • 74
  • 132
  • you might have to use `interp` on the `x` and `y` components of the returned object ... – Ben Bolker Aug 03 '17 at 03:20
  • are you looking for something like this: `x <- 2; approx(d$x,d$y,xout = x)`? – AK88 Aug 03 '17 at 03:25
  • If you mean that you want to extract the x values at a given location in the data set, then you can just use `d$x[3]` for a the third value. or `d$y[5]` for the fifth location y result, you can extract any value you want this way. – sconfluentus Aug 03 '17 at 03:38
  • @AK88, yeah, something like that. Do you know how off the linear interpolation would be from the actual density estimate provided by the function? – Adrian Aug 03 '17 at 04:29
  • unfortunately, have no idea ... – AK88 Aug 03 '17 at 04:55
  • I think `approx` will be fine. Even the documentation of `stats::density` mentions that they will use `approx` if you request to compute the density at more then 512 points. – AEF Aug 03 '17 at 08:16

1 Answers1

0

If I understand you correctly, you want the probabilities where the x value equals some number (3 or 4 as in my solution)?

d <- density(faithful$eruptions, bw = "sj")
densityDF <- data.frame(xVals = d$x, prob = d$y)
densityDF$xVals <- round(densityDF$xVals)

densitySearch <- densityDF[densityDF$xVals %in% c(3,4),]

Result:

   xVals       prob
157     3 0.11229482
158     3 0.10721410
159     3 0.10230912
160     3 0.09765156
161     3 0.09318662
162     3 0.08891621
DataTx
  • 1,839
  • 3
  • 26
  • 49