wtd_mean: Calculate a weighted mean

wtd_meanR Documentation

Calculate a weighted mean

Description

This is an improvement on weighted.mean in base-r.

Usage

wtd_mean(x, w = NULL, error = F)

Arguments

x

(num vector) A vector of values.

w

(num vector) A vector of weights.

error

(lgl scalr) Whether to throw an error if there is no data at all or no pairwise complete cases. Default yes.

Details

The original function returns NA when there are missing values in the weights vector despite na.rm=T. This function avoids that problem. It also returns a useful error message if there are no complete cases. The function wraps base-r's function.

Examples

set.seed(1)
X = rnorm(100)
set.seed(1)
W = runif(100)
wtd_mean(X) # not using weights
mean(X) #same as above
wtd_mean(X, W) #slightly different

Deleetdk/kirkegaard documentation built on April 22, 2024, 5:22 p.m.