Search code examples
rkernel-density

Custom Kernel in kdensity package in R


I need help with inserting custom made kernels into R packages, is this possible? In the kdensity package it states "The kernel function Can be chosen from the list of built-in kernels or be custom made."

I found a tutorial online on how custom kernels could be inserted using the kdensity package, however, it is still unclear to me how it actually works.

Here is the link to the tutorial: (https://cran.r-project.org/web/packages/kdensity/vignettes/tutorial.html).

What I would like to be able to do is use the custom kernel 0.5e^(−|x|) with simulated random normal data (x=rnorm(100,6,2) to plot kernel estimates. Then from there, change bandwidth to see how that effects the plot.

Based off the tutorial, it gives the example of the Gaussian kernel and codes it like this:

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

Where x is the data, y is point you want to evaluate it, and h is the bandwidth.

Therefore, based off of this I created this:

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

     suport=c(-Inf,Inf)
     )

Then, I ran it in the kdensity package and got this error:

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

Something is clearly not right, I am not sure how to fix it.

Any help is appreciated!


Solution

  • Two things:

    1. support instead of suport
    2. kernel = k1 instead of kernel = "k1"

    This gives

    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