Calculate the weighted variance of x
.
Details
Calculate the weighted variance of x
via the weighted covariance
matrix (cov.wt()
). If no weights are supplied, the simple variance is
returned instead. As in weighted.mean()
, NA
s in w
are not handled
specially and will return NA
as result.
Examples
# Weighted variance
x <- rnorm(30)
w <- runif(30, 0, 1)
varW(x, w)
#> [1] 0.9165465
# Simple variance
varW(x)
#> [1] 0.8397168
stopifnot(varW(x) == var(x))
# NA handling
varW(c(x[1:29], NA), w, na.rm = TRUE) # NA in x (removed)
#> [1] 0.9325413
varW(c(x[1:29], NA), w, na.rm = FALSE) # NA in x (NA returned)
#> [1] NA
varW(x[1:29], w = c(w[1:29], NA)) # NA in w (NA returned)
#> [1] NA