How does the density
function in R incorporate weights if they are specified (assume weights sum to 1, which is what the function wants)? I mean mathematically, how does it work? I know how to look at the underlying R code for a function but not when it just returns a generic method like this:
> density
function (x, ...)
UseMethod("density")
<bytecode: 0x00000000079ee728>
<environment: namespace:stats>
The reason I'm asking is that I have made some nice side-by-side empirical density plots using unweighted and weighted samples which shows the benefits of weighting one's sample to make the distribution of covariates more balanced between groups. These were all continuous covariates. Now I want to do the same thing with dichotomous variables, but the density function isn't great for this. I want to see if I can apply the same weighting method to generate side-by-side box plots for the dichotomous covariates that I have.
This is an exercise in source code hunting, but here goes:
In density.default
, the relevant part (besides checking the weights are valid) is only the line:
y <- .Call(C_BinDist, x, weights, lo, up, n) * totMass
In the relevant source file, massdist.c
we find (comments my own):
for(R_xlen_t i = 0; i < XLENGTH(sx) ; i++) {
if(R_FINITE(x[i])) {
double xpos = (x[i] - xlo) / xdelta;
int ix = (int) floor(xpos);
double fx = xpos - ix;
double wi = w[i]; // w: weights vector
if(ixmin <= ix && ix <= ixmax) {
y[ix] += (1 - fx) * wi;
y[ix + 1] += fx * wi;
}
else if(ix == -1) y[0] += fx * wi;
else if(ix == ixmax + 1) y[ix] += (1 - fx) * wi;
}
}