kernelFun | R Documentation |
Computes 5 most popular kernel functions of orders 2 and 4 with the potential of returning an analytical convolution kernel for density cross-validation. These kernels appear in \insertCitesilverman1986densitysmoothemplik.
kernelFun(
x,
kernel = c("gaussian", "uniform", "triangular", "epanechnikov", "quartic"),
order = c(2, 4),
convolution = FALSE
)
x |
A numeric vector of values at which to compute the kernel function. |
kernel |
Kernel type: uniform, Epanechnikov, triangular, quartic, or Gaussian. |
order |
Kernel order. 2nd-order kernels are always non-negative.
*k*-th-order kernels have all moments from 1 to (k-1) equal to zero, which is
achieved by having some negative values.
|
convolution |
Logical: return the convolution kernel? (Useful for density cross-validation.) |
The kernel functions take non-zero values on [-1, 1]
, except for
the Gaussian one, which is supposed to have full support, but due to the rapid
decay, is indistinguishable from machine epsilon outside
[-8.2924, 8.2924]
.
A numeric vector of the same length as input.
ks <- c("uniform", "triangular", "epanechnikov", "quartic", "gaussian"); names(ks) <- ks
os <- c(2, 4); names(os) <- paste0("o", os)
cols <- c("#000000CC", "#0000CCCC", "#CC0000CC", "#00AA00CC", "#BB8800CC")
put.legend <- function() legend("topright", legend = ks, lty = 1, col = cols, bty = "n")
xout <- seq(-4, 4, length.out = 301)
plot(NULL, NULL, xlim = range(xout), ylim = c(0, 1.1),
xlab = "", ylab = "", main = "Unscaled kernels", bty = "n"); put.legend()
for (i in 1:5) lines(xout, kernelFun(xout, kernel = ks[i]), col = cols[i])
oldpar <- par(mfrow = c(1, 2))
plot(NULL, NULL, xlim = range(xout), ylim = c(-0.1, 0.8), xlab = "", ylab = "",
main = "4th-order kernels", bty = "n"); put.legend()
for (i in 1:5) lines(xout, kernelFun(xout, kernel = ks[i], order = 4), col = cols[i])
par(mfrow = c(1, 1))
plot(NULL, NULL, xlim = range(xout), ylim = c(-0.25, 1.4), xlab = "", ylab = "",
main = "Convolution kernels", bty = "n"); put.legend()
for (i in 1:5) {
for (j in 1:2) lines(xout, kernelFun(xout, kernel = ks[i], order = os[j],
convolution = TRUE), col = cols[i], lty = j)
}; legend("topleft", c("2nd order", "4th order"), lty = 1:2, bty = "n")
par(oldpar)
# All kernels integrate to correct values; we compute the moments
mom <- Vectorize(function(k, o, m, c) integrate(function(x) x^m * kernelFun(x, k, o,
convolution = c), lower = -Inf, upper = Inf)$value)
for (m in 0:4) {
cat("\nComputing integrals of x^", m, " * f(x). \nSimple unscaled kernel:\n", sep = "")
print(round(outer(os, ks, function(o, k) mom(k, o, m = m, c = FALSE)), 4))
cat("Convolution kernel:\n")
print(round(outer(os, ks, function(o, k) mom(k, o, m = m, c = TRUE)), 4))
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.