R 中 kdensity 包中的自定义内核

Custom Kernel in kdensity package in R

我需要帮助将定制内核插入 R 包,这可能吗?在 kdensity 包中它声明 "The kernel function Can be chosen from the list of built-in kernels or be custom made."

我在网上找到了一个关于如何使用 kdensity 包插入自定义内核的教程,但是,我仍然不清楚它是如何工作的。

这是教程的 link: (https://cran.r-project.org/web/packages/kdensity/vignettes/tutorial.html).

我想做的是使用自定义内核 0.5e^(−|x|) 和模拟的 运行dom 法线数据 (x=rnorm(100,6,2) 到绘制内核估计值。然后从那里更改带宽以查看这对绘图有何影响。

基于教程,给出了高斯核的例子,代码如下:

    gaussian = list(
     kernel  = function(y, x, h) dnorm((y-x)/h),
     sd      = 1,
     support = c(-Inf, Inf))

其中 x 是数据,y 是您要评估的点,h 是带宽。

因此,基于此我创建了这个:

    k1=list(
     kernel=function(y,x,h){
     inside=(y-x)/h
     0.5*exp(-1*abs(inside))
     },

     suport=c(-Inf,Inf)
     )

然后,我 运行 它在 kdensity 包中并得到这个错误:

   kde=kdensity(N,kernel = "k1",bw=0.5)
   Error: The supplied kernel ('k1') is not implemented.

显然有些地方不对,我不知道如何解决。

感谢任何帮助!

两件事:

  1. support 而不是 suport
  2. kernel = k1 而不是 kernel = "k1"

这给了

k1 <- list(
  kernel = function(y,x,h) {
    inside <- (y - x) / h
    0.5 * exp(-1 * abs(inside))},
  support = c(-Inf, Inf))
kdensity(rnorm(1000), kernel = k1, bw = 0.5)
# 
# Call:
# kdensity(x = rnorm(1000), bw = 0.5, kernel = k1)
#
# Data:      rnorm(1000) (1000 obs.)
# Bandwidth: 0.5 ('user supplied')
# Support:   (-Inf, Inf)
# Kernel:    k1
# Start:     uniform