Skip to content
Prev 16981 / 398502 Next

Weighted median

I noticed too late that my weighted quantile function contains some home-grown
functions which will not be found on your system.  Here's a version that is
self-contained:

g.quantile <- function(x, probs=seq(0,1,.25), wt, na.rm=TRUE) {
  if (missing(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")}
  ord <- order(x)
  z <- list(y=x[ord], wt=wt[ord])
  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) <- paste(format(round(100*probs, dec)), "%", sep="")
  a                                                # Returns weighted quantiles
}