Skip to content
Prev 170816 / 398506 Next

Percentiles/Quantiles with Weighting

Here is one kind of weighted quantile function.

The basic idea is very simple:

wquantile <- function( v, w, p )
  {
    v <- v[order(v)]
    w <- w[order(v)]
    v [ which.max( cumsum(w) / sum(w) >= p ) ]
  }

With some more error-checking and general clean-up, it looks like this:

# Simple weighted quantile
#
# v  A numeric vector of observations
# w  A numeric vector of positive weights
# p  The probability 0<=p<=1
#
# Nothing fancy: no interpolation etc.

# Basic idea

wquantile <- function( v, w, p )
  {
    v <- v[order(v)]
    w <- w[order(v)]
    v [ which.max( cumsum(w) / sum(w) >= p ) ]
  }

# Simple weighted quantile
#
# v  A numeric vector of observations
# w  A numeric vector of positive weights
# p  The probability 0<=p<=1
#
# Nothing fancy: no interpolation etc.

wquantile <- function(v,w=rep(1,length(v)),p=.5)
   {
     if (!is.numeric(v) || !is.numeric(w) || length(v) != length(w))
       stop("Values and weights must be equal-length numeric vectors")
     if ( !is.numeric(p) || any( p<0 | p>1 ) )
       stop("Quantiles must be 0<=p<=1")
     ranking <- order(v)
     sumw <- cumsum(w[ranking])
     if ( is.na(w[1]) || w[1]<0 ) stop("Weights must be non-negative numbers")
     plist <- sumw/sumw[length(sumw)]
     sapply(p, function(p) v [ ranking [ which.max( plist >= p ) ] ])
   }

I would appreciate any comments people have on this -- whether
correctness, efficiency, style, ....

              -s
On Tue, Feb 17, 2009 at 11:57 AM, Brigid Mooney <bkmooney at gmail.com> wrote: