这是我在 R 社区的第一篇文章,如果它很愚蠢,请原谅我。我想在 ggplot2 中使用函数 geom_density2d 和 stat_density2d 来绘制内核密度估计,但问题是它们无法处理加权数据。据我了解,这两个函数调用包 MASS 中的函数 kde2d 来进行内核密度估计。并且 kde2d 不将数据权重作为参数。
现在,我找到了这个 kde2d 的修改版本http://www.inside-r.org/node/226757,它以权重为参数,基于 kde2d 的源代码。这个函数的代码:
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) # gridpoints x
gy <- seq(lims[3], lims[4], length = n) # gridpoints y
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] # distance of each point to each grid point in x-direction
ay <- outer(gy, y, "-")/h[2] # distance of each point to each grid point in y-direction
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]) # z is the density
return(list(x = gx, y = gy, z = z))
}
我想让函数 geom_density2d 和 stat_density2d 调用 kd2d.weighted 而不是 kde2d,从而使它们接受加权数据。
我从未更改现有 R 包中的任何功能,所以我的问题是最简单的方法是什么?