[Rd] "median" accepting ordered factor

From: Christophe Genolini <cgenolin_at_u-paris10.fr>
Date: Sat, 13 Jun 2009 13:03:21 +0200

Hi the list,
The function median start by exclude the factor. Indeed, it not possible to calculate the median for a factor, but it is possible to evaluate the median for an ordered factor.
Would it be possible to change the median function to accept also ordered factor? This would be helpful specially in social science... Christophe

median <- function(x, na.rm=FALSE) UseMethod("median")

median.default <- function(x, na.rm = FALSE) {

    if(is.factor(x) & !is.ordered(x)) stop("need numeric or ordered data")     ## all other objects only need sort() & sum() to be working     if(length(names(x))) names(x) <- NULL # for e.g., c(x = NA_real_)     if(na.rm) x <- x[!is.na(x)] else if(any(is.na(x))) return(x[FALSE][NA])     n <- length(x)
    if (n == 0L) return(x[FALSE][NA])
    half <- (n + 1L) %/% 2L
    if(n %% 2L == 1L | is.ordered(x)) sort(x, partial = half)[half]     else sum(sort(x, partial = half + 0L:1L)[half + 0L:1L])/2 }

a1 <- factor(letters[c(1,2,3,2,3,1,3,5,4,3,4,1,1,1,1,1)],ordered=TRUE) a2 <- factor(letters[c(1,2,3,2,3,1,3,5,4,3,4,1,1,1,1,1,1)],ordered=TRUE) median(a1)

R-devel_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel Received on Sat 13 Jun 2009 - 11:12:59 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Sat 13 Jun 2009 - 14:35:35 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-devel. Please read the posting guide before posting to the list.

list of date sections of archive