Skip to content
Prev 388543 / 398513 Next

density with weights missing values

Den 2021-07-12 kl. 15:09, skrev Matthias Gondan:
One difference is that density has a named argument 'weights' not 
present in weighted.mean, which instead has 'w' for weights.
Annoying.

So, in your examples, the argument 'weights = ' is always ignored, at 
least for weighted.mean.default:

 > stats:::weighted.mean.default
function (x, w, ..., na.rm = FALSE)
{
     if (missing(w)) {
         if (na.rm)
             x <- x[!is.na(x)]
         return(sum(x)/length(x))
     }
     if (length(w) != length(x))
         stop("'x' and 'w' must have the same length")
     if (na.rm) {
         i <- !is.na(x)
         w <- w[i]
         x <- x[i]
     }
     sum((x * w)[w != 0])/sum(w)
}

But, using 'w' for weights, missing values in weights will work only if 
na.rm = TRUE and they match missing values in x. As documented.

[...]
and no warning for sum(w) != 1

That's because the weights w are normalized (after removing weights 
corresponding to missing values in x).

G,