Learn R Programming

npreg (version 1.1.0)

wtd.var: Weighted Variance and Standard Deviation

Description

Generic function for calculating weighted variance or standard deviation of a vector.

Usage

wtd.var(x, weights, na.rm = FALSE)

wtd.sd(x, weights, na.rm = FALSE)

Value

Returns the weighted variance or standard deviation.

Arguments

x

Numerical or logical vector.

weights

Vector of non-negative weights.

na.rm

Logical indicating whether NA values should be removed before calculation.

Author

Nathaniel E. Helwig <helwig@umn.edu>

Details

The weighted variance is defined as

(n / (n - 1)) * sum(weights * (x - xbar)^2) / sum(weights)

where n is the number of observations with non-zero weights, and xbar is the weighted mean computed via the wtd.mean function.

The weighted standard deviation is the square root of the weighted variance.

See Also

wtd.mean for weighted mean 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
xbar <- wtd.mean(x, w)

# weighted variance
wtd.var(x, w)
(10 / 9) * sum(w * (x - xbar)^2) / sum(w)

# weighted standard deviation
wtd.sd(x, w)
sqrt((10 / 9) * sum(w * (x - xbar)^2) / sum(w))

Run the code above in your browser using DataLab