Learn R Programming

npreg (version 1.1.0)

wtd.quantile: 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)

Value

Returns the weighted quantiles corresponding to the input probabilities.

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.

Author

Nathaniel E. Helwig <helwig@umn.edu>

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.

See Also

wtd.mean for weighted mean calculations

wtd.var for weighted variance calculations

Examples

Run this code
# 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))

Run the code above in your browser using DataLab