How do I save the result from density(dataset) as a function? So then if I want to evaluate point x in that function, it gives me the probability from that density(dataset)?
As you can see below, density
function retuns a list containing x
and y
values of density function which can be used to create a "interpolation" function using approxfun
function.
d <- density(rnorm(100))
str(d)
## List of 7
## $ x : num [1:512] -3.85 -3.83 -3.82 -3.8 -3.79 ...
## $ y : num [1:512] 0.000135 0.000154 0.000176 0.0002 0.000227 ...
## $ bw : num 0.332
## $ n : int 100
## $ call : language density.default(x = rnorm(100))
## $ data.name: chr "rnorm(100)"
## $ has.na : logi FALSE
## - attr(*, "class")= chr "density"
pdf <- approxfun(d)
pdf(2)
## [1] 0.05439069
approxfun
gives linear approximation
To verify lets plot the original density d
plot(d)
Now lets plot the interpolated values using the new function pdf
that we created
x <- seq(-2,2,by=0.01)
points(x, pdf(x))
(The value of a density at a specific point is NOT the probability of that point.)
> d <- density(sample(10,1000000,replace=TRUE,prob=(1:10)/sum(1:10)))
> plot(d)
# the density is estimated at a specified number of points. I find the closest to
# the point I want to know the density's value of and then get that value.
> fd <- function(x) d$y[which.min(abs(d$x - x))]
> fd(6)
[1] 0.311895
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With