Learn R Programming

fritools (version 3.3.0)

weighted_variance: Calculate a Weighted Variance

Description

Calculate a weighted variance.

Usage

weighted_variance(x, ...)

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

# S3 method for 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.

See Also

Other bits and pieces: golden_ratio(), is_difftime_less(), is_valid_primary_key(), r_cmd_install(), round_half_away_from_zero(), str2num(), strip_off_attributes(), tapply(), throw()

Examples

Run this code
# NOT RUN {
## 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")
# }

Run the code above in your browser using DataLab