Calculate probability from density function

I built a density function, and now I want to calculate the probability that a new data point will “fall” into the selected interval (say, a = 3, b = 7). So I'm looking for:

P(a<x<=b)

Some sample data:

df<- data.frame(x=c(sample(6:9, 50, replace=TRUE), sample(18:23, 25, replace=TRUE)))

dens<- density(df$x)

I will be glad to hear about any solution, but preferably in the r base

Thank you in advance

+4
source share
1 answer

You need to get the density as a function (using approxfun), and then integrate the function over the required limits.

integrate(approxfun(dens), lower=3, upper=7)
0.258064 with absolute error < 3.7e-05

## Consistency check
integrate(approxfun(dens), lower=0, upper=30)
0.9996092 with absolute error < 1.8e-05
+3
source

Source: https://habr.com/ru/post/1675439/


All Articles