Skip to content
Prev 131012 / 398502 Next

R function for percentrank

Its a bit tricky if you want to get it to work exactly the same as
Excel even in the presence of runs but in terms of the R approx function
I think percentrank corresponds to ties = "min" if the value is among those
in the table and ties = "ordered" otherwise so:

percentrank <- function(table, x = table) {
   table <- sort(table)
   ties <- ifelse(match(x, table, nomatch = 0), "min", "ordered")
   len <- length(table)
   f <- function(x, ties)
      (approx(table, seq(0, len = len), x, ties = ties)$y) / (len - 1)
   mapply(f, x, ties)
}

# test
tab <- c(1, 1, 2, 2, 3, 3)
percentrank(tab, 2:6/2) # c(0, .3, .4, .7, .8)

which is the same result as Excel 2007 gives.
On Dec 1, 2007 6:37 AM, tom soyer <tom.soyer at gmail.com> wrote: