wtd.mean | R Documentation |
Generic function for calculating the weighted (and possibly trimmed) arithmetic mean.
wtd.mean(x, weights, trim = 0, na.rm = FALSE)
x |
Numerical or logical vector. |
weights |
Vector of non-negative weights. |
trim |
Fraction [0, 0.5) of observations trimmed from each end before calculating mean. |
na.rm |
Logical indicating whether |
If weights
are missing, the weights are defined to be a vector of ones (which is the same as the unweighted arithmetic mean).
If trim
is non-zero, then trim
observations are deleted from each end before the (weighted) mean is computed. The quantiles used for trimming are defined using the wtd.quantile
function.
Returns the weighted and/or trimmed arithmetic mean.
The weighted (and possible trimmed) mean is defined as:
sum(weights * x) / sum(weights)
where x
is the (possibly trimmed version of the) input data.
Nathaniel E. Helwig <helwig@umn.edu>
wtd.var
for weighted variance calculations
wtd.quantile
for weighted quantile calculations
# generate data and weights
set.seed(1)
x <- rnorm(10)
w <- rpois(10, lambda = 10)
# weighted mean
wtd.mean(x, w)
sum(x * w) / sum(w)
# trimmed mean
q <- quantile(x, probs = c(0.1, 0.9), type = 4)
i <- which(x < q[1] | x > q[2])
mean(x[-i])
wtd.mean(x, trim = 0.1)
# weighted and trimmed mean
q <- wtd.quantile(x, w, probs = c(0.1, 0.9))
i <- which(x < q[1] | x > q[2])
wtd.mean(x[-i], w[-i])
wtd.mean(x, w, trim = 0.1)
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.