weighted_variance: Calculate a Weighted Variance

View source: R/weighted_variance.R

weighted_varianceR Documentation

Calculate a Weighted Variance

Description

Calculate a weighted variance.

Usage

weighted_variance(x, ...)

## S3 method for class 'numeric'
weighted_variance(x, weights, weights_counts = NULL, ...)

## S3 method for class 'data.frame'
weighted_variance(x, var, weight, ...)

Arguments

x

A numeric vector or data.frame.

...

Other arguments ignored.

weights

A vector of weights.

weights_counts

Are the weights counts of the data? If so, we can calculate the unbiased sample variance, otherwise we calculate the biased (maximum likelihood estimator of the) sample variance.

var

The name of the column in x giving the variable of interest.

weight

The name of the column in x giving the weights.

Details

The data.frame method is meant for use with tapply, see examples.

Value

A numeric giving the (weighted) variance of x.

See Also

Other statistics: column_sums(), count_groups(), relative_difference(), round_half_away_from_zero(), sloboda()

Examples

## GPA from Siegel 1994
wt <- c(5,  5,  4,  1)/15
x <- c(3.7,3.3,3.5,2.8)
var(x)
weighted_variance(x = x)
weighted_variance(x = x, weights = wt)
weighted_variance(x = x, weights = wt, weights_counts = TRUE)
weights <- c(5,  5,  4,  1)
weighted_variance(x = x, weights = weights)
weighted_variance(x = x, weights = weights, weights_counts = FALSE)
weighted_variance(x = data.frame(x, wt), var = "x",
                             weight = "wt")
# apply by groups:
fritools::tapply(object = mtcars,
                 index = list(mtcars[["cyl"]], mtcars[["vs"]]),
                 func = weighted_variance, var = "mpg", w = "wt")

fritools documentation built on Nov. 19, 2023, 1:06 a.m.