This is my first post in the R community, so forgive me if this is stupid. I would like to use the functions geom_density2d and stat_density2d in ggplot2 to calculate kernel density estimates, but the problem is that they cannot handle weighted data. From what I understand, these two functions call the kde2d function from the MASS package to make an estimate of the kernel density. And kde2d does not accept data as a parameter.
Now I have found this modified version of kde2d http://www.inside-r.org/node/226757 , which takes weight as a parameter and is based on the source code of kde2d. The code for this function is:
kde2d.weighted <- function (x, y, w, h, n = 25, lims = c(range(x), range(y))) {
nx <- length(x)
if (length(y) != nx)
stop("data vectors must be the same length")
if (length(w) != nx & length(w) != 1)
stop("weight vectors must be 1 or length of data")
gx <- seq(lims[1], lims[2], length = n)
gy <- seq(lims[3], lims[4], length = n)
if (missing(h))
h <- c(bandwidth.nrd(x), bandwidth.nrd(y));
if (missing(w))
w <- numeric(nx)+1;
h <- h/4
ax <- outer(gx, x, "-")/h[1]
ay <- outer(gy, y, "-")/h[2]
z <- (matrix(rep(w,n), nrow=n, ncol=nx, byrow=TRUE)*matrix(dnorm(ax), n, nx)) %*% t(matrix(dnorm(ay), n, nx))/(sum(w) * h[1] * h[2])
return(list(x = gx, y = gy, z = z))
}
geom_density2d stat_density2d kd2d.weighted kde2d .
R, - ?