R/var-wt.R

Defines functions var_wt

Documented in var_wt

#' Calculates the weighted variance
#'
#' @param x numeric vector
#' @param wt weights 
#' @param na.rm If `TRUE`, indices where `x` is NA will be removed
#'
#' @return A numeric vector containing weighted variance of the elements of `x`
#' @export 
#' 
#' @examples
#' x <- sample(1:10, size = 10, replace = TRUE)
#' x.weight <- seq(0, 1, length.out = 10)
#' var_wt(x, wt = x.weight)
var_wt<- function(x, wt, na.rm = FALSE) {
  
  if(na.rm){
  	i <-  !is.na(x)
    x <- x[i]
    wt <- wt[i]
  }
  s <- sum(wt)
  
  return((sum(wt*x^2) * s - sum(wt*x)^2) / (s^2 - sum(wt^2)))
}

Try the rineq package in your browser

Any scripts or data that you put into this service are public.

rineq documentation built on April 4, 2025, 4:47 a.m.