wtd.quantile: Weighted Quantiles

View source: R/wtd.quantile.R

wtd.quantileR Documentation

Weighted Quantiles

Description

Generic function for calculating weighted quantiles.

Usage

wtd.quantile(x, weights, probs = seq(0, 1, 0.25), 
             na.rm = FALSE, names = TRUE)

Arguments

x

Numerical or logical vector.

weights

Vector of non-negative weights.

probs

Numeric vector of probabilities with values in [0,1].

na.rm

Logical indicating whether NA values should be removed before calculation.

names

Logical indicating if the result should have names corresponding to the probabilities.

Details

If weights are missing, the weights are defined to be a vector of ones (which is the same as the unweighted quantiles).

The weighted quantiles are computed by linearly interpolating the empirical cdf via the approx function.

Value

Returns the weighted quantiles corresponding to the input probabilities.

Note

If the weights are all equal (or missing), the resulting quantiles are equivalent to those produced by the quantile function using the 'type = 4' argument.

Author(s)

Nathaniel E. Helwig <helwig@umn.edu>

See Also

wtd.mean for weighted mean calculations

wtd.var for weighted variance calculations

Examples

# generate data and weights
set.seed(1)
x <- rnorm(10)
w <- rpois(10, lambda = 10)

# unweighted quantiles
quantile(x, probs = c(0.1, 0.9), type = 4)
wtd.quantile(x, probs = c(0.1, 0.9))

# weighted quantiles
sx <- sort(x, index.return = TRUE)
sw <- w[sx$ix]
ecdf <- cumsum(sw) / sum(sw)
approx(x = ecdf, y = sx$x, xout = c(0.1, 0.9), rule = 2)$y
wtd.quantile(x, w, probs = c(0.1, 0.9))


npreg documentation built on May 29, 2024, 4:17 a.m.

Related to wtd.quantile in npreg...