3

I need to find the median of an ordinal (i.e. ordered factor) in R.

I couldn't find a method in the standard library to do this, so I came up with the following clunky solution:

ordinal.median <- function(x){
        lbls <- levels(x)
        new.vars <- c(NA, 1:length(lbls))
        new.vars[1] <- median(as.numeric(x))
        return(factor(new.vars, labels=lbls, ordered=T)[1])
}

What would be the idiomatic solution to this in R?

1
  • 3
    quantile(x,0.5,type=c(1,3)) handle non-numeric x
    – James
    Nov 3, 2012 at 7:37

2 Answers 2

6

You can simplify it a bit (and note that ordered is the class for ordinal factors, so you can call this with just median(o) where o is your variable):

median.ordered <- function(x)
{
    levs <- levels(x)
    m <- median(as.integer(x))
    if(floor(m) != m)
    {
      warning("Median is between two values; using the first one")
      m <- floor(m)
    }
    ordered(m, labels = levs, levels = seq_along(levs))
}

Usage:

median(ordered(c("A", "B", "C"))) 
median(ordered(c("A", "B", "A", "B")))
2
  • You should probably add a warning when you have to "divide" the mid-point. For example, what is the median of c("A", "A", "B", "B") Oct 28, 2011 at 10:13
  • @csgillespie: Agreed. I've added the warning. Oct 28, 2011 at 11:04
3
quantile(ordered_factor, .5, type=1)

See help page for discussion of the type= option.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.