Functions to calculate a weighted mean or any other metric.

weighted_mean(x, w, na.rm = getOption("na.rm", FALSE))

weighted_median(x, w, na.rm = getOption("na.rm", FALSE))

weighted_Q1(x, w, na.rm = getOption("na.rm", FALSE))

weighted_Q3(x, w, na.rm = getOption("na.rm", FALSE))

weighted_fn(x, w, fun, ...)

Arguments

x

vector of values

w

weights, length 1 or length of x

na.rm

a logical to indicate whether empty must be removed from x

fun

function to apply

...

arguments passed on to fun

Default values of na.rm

This 'certestats' package supports a global default setting for na.rm in many mathematical functions. This can be set with options(na.rm = TRUE) or options(na.rm = FALSE).

For normality(), quantile() and IQR(), this also applies to the type argument. The default, type = 7, is the default of base R. Use type = 6 to comply with SPSS.

Examples

x <- c(1:10)
y <- c(1:10)

mean(x)
#> [1] 5.5
weighted_mean(x, y)
#> [1] 7

# essentially equal to:
mean(rep(x, y))
#> [1] 7

x <- c(0:1000)
y <- c(0:1000)
mean(x)
#> [1] 500
weighted_mean(x, y)
#> [1] 667
weighted_median(x, y)
#> [1] 707
weighted_Q1(x, y)
#> [1] 500
weighted_Q3(x, y)
#> [1] 866
weighted_fn(x, y, quantile, c(0.01, 0.99))
#>  1% 99% 
#> 100 995