demoKde (version 0.9-4)

kde: Univariate kernel density estimation directly in R code.

Description

This function behaves similarly to the density function of the stats package, but uses only R code. It is a demonstration function intended to show how kernel density estimates are computed, at least conceptually. Unlike density, the kernel may be supplied as an R function in a standard form. Example kernel functions are provided. For computational efficiency, the density function of the stats package is far superior.

Usage

kde(x, bw = bw.nrd0, kernel = kernelGaussian, n = 4096,
    from = min(x) - 3 * sd, to = max(x) + 3 * sd,
    adjust = 1, ...)

Arguments

x

Univeriate sample. Must be numeric.

bw

Either an explicit numeric bandwidth to be used for the kernel, or a function used to calculate it.

kernel

The kernel function to be used. Must have the same argument sequence as kernelGaussian, with the same meanings.

n

Then number of points covering the range at which to evaluate the KDE. More gives a smoother display of the result; fewer gives a quicker and more memory efficient computation.

from

Lower boundary for the computed KDE.

to

Upper boundary for the computed KDE.

adjust

Adjustment factor to be used for the bandwidth.

Additional arguments, if needed, to be supplied to the kernel function.

Value

An object of class “density”, with essentially the same structure as objects generated by the density of the stats package. plot and allied methods should apply.

Details

This is a demonstration function intended to show, via R code, the way in which a kernel density estimate is computed.

For samples which are not too large the computation is reasonably efficient, but for serious computations the standard function density, or some alternative, should be used.

See Also

kernelBiweight and aliases; density.

Examples

Run this code
# NOT RUN {
if(require("graphics")) {
  with(MASS::geyser, {
      hist(waiting, freq=FALSE, main="", border="grey", las=1)
      lines(stats::density(waiting), col="skyblue", lwd=8)
      lines(kde(waiting))
      lines(kde(waiting, kernel = kernelUniform), col="red")
      rug(jitter(waiting), col="blue")
      legend("topleft", c("density histogram",
        "KDE gaussian (denstiy)", "KDE gaussian (kde)",
        "KDE rectangular (kde)"), lty = "solid", lwd=c(1,8,1,1),
        col=c("grey", "skyblue", "black", "red"), bty="n")
  })
}
# }

Run the code above in your browser using DataCamp Workspace