# [Rd] bug in apply with median

**Peter Dalgaard BSA
**
p.dalgaard@biostat.ku.dk

*23 Sep 2000 16:55:58 +0200*

Larry Ammann <ammann@metronet.com> writes:
>* 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:
*
for ( i in 1:1000 ) cat("Data frames are not matrices!\n")
>* X<-matrix(c(1:8,NA),3,3)
*>* X
* [,1] [,2] [,3]
[1,] 1 4 7
[2,] 2 5 8
[3,] 3 6 NA
>* apply(X,2,median,na.rm=T)
*[1] 2.0 5.0 7.5
Works fine.
However,
>* Z<-data.frame(X)
*>* apply(Z,2,median,na.rm=T)
*Error in names(x) == ans.names : comparison (1) is possible only for vector types
Question is whether this is a bug. Apply() never promised to work on
non-arrays. When applied columnwise, it would anyway be more obvious
to use
>* sapply(Z,median,na.rm=T)
* X1 X2 X3
2.0 5.0 7.5
--
O__ ---- Peter Dalgaard Blegdamsvej 3
c/ /'_ --- Dept. of Biostatistics 2200 Cph. N
(*) \(*) -- University of Copenhagen Denmark Ph: (+45) 35327918
~~~~~~~~~~ - (p.dalgaard@biostat.ku.dk) FAX: (+45) 35327907
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._