Skip to content

Weighted median

1 message · David Brahm

#
Henrik Bengtsson <hb at maths.lth.se> wrote:

        
Markus Jantti <markus.jantti at iki.fi> wrote:
Here's a weighted quantile function I wrote that I believe reproduces the
standard interpolation for wt=rep(1,length(x)).  The interpolation is done with
approx().  Haven't looked at it in a while, so caveat emptor.

g.quantile <- function(x, probs=seq(0,1,.25), wt=NULL, na.rm=T) {
  if (is.null(wt)) return(quantile(x, probs, na.rm))
  q <- !is.na(x) & !is.na(wt)
  if (!all(q)) {if (na.rm) {x<-x[q]; wt<-wt[q]} else stop("NA's")}
  z <- g.sort(list(y=x, wt=wt), "y")
  z$x <- (cumsum(z$wt) - z$wt[1]) / (sum(z$wt) - z$wt[1])    # 0 to 1 inclusive
  a <- approx(z$x, z$y, probs)$y
  dec <- if (length(probs)>1) 2-log10(diff(range(probs))) else 2
  names(a) <- format(round(100*probs, dec)) %&% "%"
  a                                                # Returns weighted quantiles
}