Learn R Programming

rvec (version 0.0.7)

weighted_mean: Calculate Weighted Summaries

Description

Calculate weighted

  • means

  • medians

  • MADs (mean absolute deviations)

  • variances

  • standard deviations.

These functions all work with ordinary vectors and with rvecs.

Usage

weighted_mean(x, wt = NULL, na_rm = FALSE)

# S3 method for default weighted_mean(x, wt = NULL, na_rm = FALSE)

# S3 method for rvec weighted_mean(x, wt = NULL, na_rm = FALSE)

weighted_mad(x, wt = NULL, na_rm = FALSE)

# S3 method for default weighted_mad(x, wt = NULL, na_rm = FALSE)

# S3 method for rvec weighted_mad(x, wt = NULL, na_rm = FALSE)

weighted_median(x, wt = NULL, na_rm = FALSE)

# S3 method for default weighted_median(x, wt = NULL, na_rm = FALSE)

# S3 method for rvec weighted_median(x, wt = NULL, na_rm = FALSE)

weighted_sd(x, wt = NULL, na_rm = FALSE)

# S3 method for default weighted_sd(x, wt = NULL, na_rm = FALSE)

# S3 method for rvec weighted_sd(x, wt = NULL, na_rm = FALSE)

weighted_var(x, wt = NULL, na_rm = FALSE)

# S3 method for default weighted_var(x, wt = NULL, na_rm = FALSE)

# S3 method for rvec weighted_var(x, wt = NULL, na_rm = FALSE)

Value

If x or wt or is rvec, then an rvec of length 1. Otherwise, a scalar.

Arguments

x

Quantity being summarised. An ordinary vector or an rvec.

wt

Weights. An ordinary vector, an rvec, or NULL (the default.) If NULL, an unweighted summary is returned.

na_rm

Whether to remove NAs in x or wt before calculating. Default is FALSE. See matrixStats::weightedMean() for a description of the algorithm used.

Details

x and wt must have the same length.

Internally the calculations are done by matrixStats functions such as matrixStats::weightedMean() and matrixStats::colWeightedMeans().

See Also

  • Functions mean(), median(), mad(), var(), sd() for unweighted data all have methods for rvecs

  • The original matrixStats weighted summary functions have additional options not implemented in the functions here.

  • weighted.mean() is a base R function for weighted data

  • For numeric summaries of draws in an rvec, use draws_median(), draws_mean, draws_quantile(), draws_fun().

Examples

Run this code
## 'x' is rvec, 'wt' is ordinary vector
v <- rvec(list(c(1, 11),
               c(2, 12),
               c(7, 17)))
weights <- c(40, 80, 72)
weighted_mean(v, wt = weights)

## 'x' is ordinary vector, 'wt' is rvec
y <- c(1, 2, 3)
w <- rvec(list(c(100, 200),
               c(210, 889),
               c(200, 200)))
weighted_mean(y, wt = w)
weighted_mean(y, wt = w, na_rm = TRUE)

Run the code above in your browser using DataLab