Skip to content
Back to formatted view

Raw Message

Message-ID: <8b356f880902172025r5bb8511eoe62fd6a757e83986@mail.gmail.com>
Date: 2009-02-18T04:25:38Z
From: Stavros Macrakis
Subject: Percentiles/Quantiles with Weighting
In-Reply-To: <8b356f880902172024n6e8d3c7ara83b0498359f53ca@mail.gmail.com>

Some minor improvements and corrections below

# Simple weighted quantile
#
# v  A vector of sortable observations
# w A numeric vector of positive weights
# p  The quantile 0<=p<=1
#
# Nothing fancy: no interpolation etc.; NA cases not thought through

 wquantile <- function(v,w=rep(1,length(v)),p=.5)
  {
    if ( !is.numeric(w) || length(v) != length(w) )
      stop("Values and weights must be equal-length vectors")
    if ( !is.numeric(p) || any( p<0 | p>1) )
      stop("Quantiles must be 0<=p<=1")
    if ( min(w) < 0 ) stop("Weights must be non-negative numbers")
    ranking <- order(v)
    sumw <- cumsum(w[ranking])
    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