[R] Weighted median

David Brahm brahm at alum.mit.edu
Thu Feb 7 15:57:47 CET 2002


Henrik Bengtsson <hb at maths.lth.se> wrote:
> Is there a weighted median function out there...

Markus Jantti <markus.jantti at iki.fi> wrote:
> I have written the following functions for my own use but am unhappy with
> them [because] I wanted to define a weighted.quantile function that
> reproduced the R quantile function for the unweighted case (R:s quantile does
> some smart interpolating), but I did not manage to do so.

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
}

-- 
                              -- David Brahm (brahm at alum.mit.edu)
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list