kde_2d: Two Dimensional Kernel Density Estimate

Description Usage Arguments Value Examples

Description

A pure R implementation of two direct algorithms.

Usage

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
kde_2d(
  x,
  y,
  N = 256,
  bw = c(x = bw.nrd0(x), y = bw.nrd0(y)),
  lower_x = limits$x$lower,
  upper_x = limits$x$upper,
  lower_y = limits$y$lower,
  upper_y = limits$y$upper,
  k = 1
)

## S3 method for class 'kde_2d'
print(x, ...)

## S3 method for class 'kde_2d'
plot(
  x,
  ...,
  xlab = bquote(italic(.(x$data_name[["x"]]))),
  ylab = bquote(italic(.(x$data_name[["y"]]))),
  col = hcl.colors(25, rev = TRUE)
)

## S3 method for class 'kde_2d'
as.data.frame(
  x,
  row.names,
  optional,
  ...,
  borders = FALSE,
  responseName = "density"
)

Arguments

x

Numeric vector or, in generics, a kde object

y

Numeric vector of the response Variables

N

Integer: number of equally spaced points for the kde. May be one or two for x and y respectively

bw

Numeric: bandwidth(s) for x and y kernels respectively. A single value will be duplicated.

lower_x, upper_x, lower_y, upper_y

Numeric: kde range limits

k

Ineger: number of bandwidths by which to increase the range for the default limits.

...

Extra arguments passed on to methods.

xlab, ylab, col

base graphics parameters

row.names, optional

As for the as.data.frame generic

borders

logical: should zero borders be included around the density when the object is coerced to a data frame.

responseName

character string: name for the density vector.

Value

An object of class "kde_2d"

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
set.seed(1234)
x_value <- abs(rnorm(5000))
y_value <- rnorm(x_value)
kxy <- kde_2d(x_value, y_value, lower_x = 0)
kxy
if("package:ggplot2" %in% search()) {
    ggplot(within(as.data.frame(kxy),
                  pDens <- 2*dnorm(x_value)*dnorm(y_value))) +
      aes(x = x_value, y = y_value) +
      geom_raster(aes(fill = density)) +
      geom_contour(aes(z = pDens), colour = "black") +
      scale_fill_viridis_c(direction = -1) +
      theme_bw() + theme(legend.position = "none")
} else {
  with(unclass(kxy), {
    oldPar <- par(mar = c(3, 3, 1, 1) + 0.1, las = 1, mgp = c(1.5, 0.5, 0),
                 cex.axis = 0.7, cex.lab = 0.8, tck = -0.015)
    plot(kxy)
    contour(x, y, z = outer(x, y, function(x, y) 2*dnorm(x)*dnorm(y)),
            nlevels = 6, add = TRUE)
    box()
    par(oldPar)
  })
}

BillVenables/kdeR documentation built on April 12, 2021, 1:51 p.m.