简体   繁体   中英

Univariate adaptive kernel density estimation in R

Is there an R function which can calculate an adaptive kernel density function for univariate observations. What about akj (package quantreg )? Thanks.

I do not know about the package but it is quite simple to implement it yourself (this will also make your understand exactly what you are doing), for example lets take these values in the plan:

g = 5
n = 100
set.seed(g)
df = data.frame(x = unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i))),
                y= unlist(lapply(1:g, function(i) rnorm(n/g, runif(1)*i))))

plot(df)

在此处输入图片说明

Let's assume you want to estimate the density at three point x1 = c(6,-1) , x2 = c(0.3, 2) , x3=c(3, -0.5) on this distribution. The density should be weak on x1, high on x2 and the density on x3 should be between these two low and high densities:

points(6,-1, col='red', pch=19)
points(0.3,2, col='blue', pch=19)
points(3,-0.5, col='green', pch=19)

在此处输入图片说明

According to the definition of an adaptative kernel density function:

http://en.wikipedia.org/wiki/Variable_kernel_density_estimation

library(functional)

gaussianKernel = function(u, h) exp(-sum(u^2)/(2*h^2))

densityFunction = function(x, df, ker, h)
{
    difference = t(t(df) - x)
    W = sum(apply(difference, 1, ker, h=h))
    W/(nrow(df)*(h^(length(df))))
}

myDensityFunction = Curry(densityFunction, df=df, ker=gaussianKernel , h=2)

And we have the confirmation of the intuitive result: 0 <= P(x1) < P(x3) < P(x2) <=1

#> myDensityFunction(x1)
#[1] 0.02140895
#> myDensityFunction(x2)
#[1] 0.1146402
#> myDensityFunction(x3)
#[1] 0.09341908

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM