# [Rd] bug in apply with median

**Larry Ammann
**
ammann@metronet.com

*Sat, 23 Sep 2000 08:48:49 -0500*

I have found a problem in R version 1.1.1 when using apply with the
median function.
The problem can be illustrated with the following data matrix:
X1 X2 X3
1 2 3
4 5 6
7 8 NA
Enter this data matrix as X and then try
apply(X,2,median,na.rm=T)
The problem here is that the median function returns a named scalar if
the number of
observations is odd, but returns an unnamed scalar if the number of
observations is
even. This confuses the apply function in this case at:
ans.names <- names(ans[[1]])
if (!ans.list)
ans.list <- any(unlist(lapply(ans, length)) != l.ans)
if (!ans.list && length(ans.names)) {
all.same <- sapply(ans, function(x) all(names(x) == ans.names))
#here is the offending line
if (!all(all.same))
ans.names <- NULL
}
This problem does not occur with S-Plus. My quick solution was to use
the quantile function
instead of the median function:
apply(X,2,quantile,probs=.5,na.rm=T)
One way of fixing the problem then is to redefine median as
median <- function(x,na.rm=F,names=T)
quantile(x,probs=.5,na.rm=na.rm,names=names)
I don't know if this is a long-term solution though, since there may be
other functions with inconsistent
naming policies that can confuse apply as it is currently written.
Larry Ammann
Professor of Mathematical Sciences
University of Texas at Dallas
http://www.utdallas.edu/~ammann
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-devel 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-devel-request@stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._