Calculates weighted quantiles based on the generalized inverse of the weighted ECDF.
If no weights are passed, uses stats::quantile()
.
weighted_quantile(
x,
w = NULL,
probs = seq(0, 1, 0.25),
na.rm = TRUE,
names = TRUE,
...
)
Numeric vector.
Optional vector of non-negative case weights.
Vector of probabilities.
Ignore missing data? Default is TRUE
.
Return names? Default is TRUE
.
Further arguments passed to stats::quantile()
in the unweighted case.
Not used in the weighted case.
A length-one numeric vector.
n <- 10
x <- seq_len(n)
quantile(x)
#> 0% 25% 50% 75% 100%
#> 1.00 3.25 5.50 7.75 10.00
weighted_quantile(x)
#> 0% 25% 50% 75% 100%
#> 1.00 3.25 5.50 7.75 10.00
weighted_quantile(x, w = rep(1, n))
#> 0% 25% 50% 75% 100%
#> 1 3 6 8 10
quantile(x, type = 1)
#> 0% 25% 50% 75% 100%
#> 1 3 5 8 10
weighted_quantile(x, w = x) # same as Hmisc::wtd.quantile()
#> 0% 25% 50% 75% 100%
#> 1 5 7 9 10
weighted_quantile(x, w = x, names = FALSE)
#> [1] 1 5 7 9 10
weighted_quantile(x, w = x, probs = 0.5, names = FALSE)
#> [1] 7
# Example with integer weights
x <- c(1, 1:11, 11, 11)
w <- seq_along(x)
weighted_quantile(x, w)
#> 0% 25% 50% 75% 100%
#> 1 6 9 11 11
quantile(rep(x, w)) # same
#> 0% 25% 50% 75% 100%
#> 1 6 9 11 11