R中的单变量自适应核密度估计

时间:2015-04-04 13:07:35

标签: r kernel-density

是否有R函数可以计算单变量观测的自适应核密度函数。那么akj(包quantreg)呢?感谢。

1 个答案:

答案 0 :(得分:0)

我不知道这个包,但是自己实现它很简单(这也会让你明白你正在做什么),例如让我们在计划中采用这些值:

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)

enter image description here

假设您要估算此分布上三点x1 = c(6,-1)x2 = c(0.3, 2)x3=c(3, -0.5)的密度。密度应该在x1上较弱,在x2上较高,x3上的密度应在这两个低密度和高密度之间:

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

enter image description here

根据适应性核密度函数的定义:

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)

我们确认了直观的结果:0 <= P(x1) < P(x3) < P(x2) <=1

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