Search code examples
rkernel-density

R: how to obtain specific density estimates


# 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?


Solution

  • 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