Learn R Programming

npreg (version 1.1.0)

wtd.mean: Weighted Arithmetic Mean

Description

Generic function for calculating the weighted (and possibly trimmed) arithmetic mean.

Usage

wtd.mean(x, weights, trim = 0, na.rm = FALSE)

Value

Returns the weighted and/or trimmed arithmetic mean.

Arguments

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 NA values should be removed before calculation.

Author

Nathaniel E. Helwig <helwig@umn.edu>

Details

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.

See Also

wtd.var for weighted variance calculations

wtd.quantile for weighted quantile calculations

Examples

Run this code
# 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)

Run the code above in your browser using DataLab