[英]How does the R 'density' function use specified weights?
How does the density
function in R incorporate weights if they are specified (assume weights sum to 1, which is what the function wants)? 如果指定了权重,则R中的
density
函数如何合并权重(假设权重之和为1,这是函数所要的)? 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:
我知道如何查看函数的底层R代码,但是当它仅返回如下通用方法时却不知道:
> 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: 在
density.default
,相关部分(除了检查权重是否有效)仅是以下行:
y <- .Call(C_BinDist, x, weights, lo, up, n) * totMass
In the relevant source file, massdist.c
we find (comments my own): 在相关的源文件
massdist.c
我们找到(注释了我自己的):
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.