Skip to content

Instantly share code, notes, and snippets.

@talgalili
Last active April 1, 2023 19:39
Show Gist options
  • Save talgalili/b92cd8cdcbfc287e331a8f27db265c00 to your computer and use it in GitHub Desktop.
Save talgalili/b92cd8cdcbfc287e331a8f27db265c00 to your computer and use it in GitHub Desktop.
Variance of the weighted mean in R
# Reference, see here: https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Variance_of_the_weighted_mean_(%CF%80-estimator_for_ratio-mean)
var_of_weighted_mean <- function(v, w = NULL, inf_rm = FALSE) {
if (is.null(w)) {
w <- rep(1, length(v))
}
if (inf_rm) {
v <- replace(v, is.infinite(v), NA)
w <- replace(w, is.infinite(w), NA)
}
w_mean <- sum(v * w) / sum(w)
squared_sum_of_w <- sum(w) ^ 2
w_var <- sum((w * (v - w_mean)) ^ 2) / squared_sum_of_w
return(w_var)
}
var_of_weighted_mean(1:4)
# 0.3125
sum((1:4 - mean(1:4))^2 / 4) / (4)
# 0.3125
var_of_weighted_mean(1:4, 1:4)
# 0.24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment