wtd.var | R Documentation |

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

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

`x` |
Numerical or logical vector. |

`weights` |
Vector of non-negative weights. |

`na.rm` |
Logical indicating whether |

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.

Returns the weighted variance or standard deviation.

If `weights`

are missing, the weights are defined to be a vector of ones (which is the same as the unweighted variance or standard deviation).

Nathaniel E. Helwig <helwig@umn.edu>

`wtd.mean`

for weighted mean calculations

`wtd.quantile`

for weighted quantile calculations

# 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))

Embedding an R snippet on your website

Add the following code to your website.

For more information on customizing the embed code, read Embedding Snippets.