How to get the function of the estimated density?

How to save a result from density (data set) as a function? So, if I want to evaluate the point x in this function, does it give me the probability of this density (data set)?

+4
source share
2 answers

As you can see below, the function densityreconfigures the list containing the values xand ydensity values ​​that can be used to create “interpolation” using the function approxfun.

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 a linear approximation

To check if the initial density allows d

plot(d)

enter image description here

pdf,

x <- seq(-2,2,by=0.01)

points(x, pdf(x))

enter image description here

+1

( .)

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

+2

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


All Articles