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)
median(a2)
______________________________________________
R-devel@r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-devel