Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to gain a function of an estimated density?

Tags:

function

r

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

like image 468
willduchateau Avatar asked Oct 01 '22 06:10

willduchateau


2 Answers

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)

enter image description here

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))

enter image description here

like image 135
CHP Avatar answered Oct 05 '22 08:10

CHP


(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

enter image description here

like image 45
Raffael Avatar answered Oct 05 '22 09:10

Raffael