\HeaderA{rowMedians.matrix}{Calculates the median for each row in a matrix}{rowMedians.matrix}
\keyword{methods}{rowMedians.matrix}
\begin{Description}\relax
Calculates the median for each row in a matrix.
\end{Description}
\begin{Usage}
\begin{verbatim}## S3 method for class 'matrix':
rowMedians(x, na.rm=FALSE, ...)\end{verbatim}
\end{Usage}
\begin{Arguments}
\begin{ldescription}
\item[\code{x}] A \code{\LinkA{numeric}{numeric}} \code{\LinkA{matrix}{matrix}}.
\item[\code{na.rm}] If \code{\LinkA{TRUE}{TRUE}}, \code{\LinkA{NA}{NA}}s are excluded before calculating the medians,
otherwise not.
\item[\code{...}] Not use.
\end{ldescription}
\end{Arguments}
\begin{Details}\relax
The main difference between this implementation and the one in
\pkg{Biobase}, \code{\LinkA{rowMedians}{rowMedians}}, is that this one handles
missing values too.
This implementation is also optimized for speed and memory to calculate
the median value whereas the \pkg{Biobase} version uses a more generic
method to estimate and quantiles, cf. \code{\LinkA{rowQ}{rowQ}}.
\end{Details}
\begin{Value}
Returns a \code{\LinkA{double}{double}} \code{\LinkA{vector}{vector}} of length equal to number of rows in \code{x}.
\end{Value}
\begin{Section}{Benchmarking}
As the example shows, this implementation is roughly 3-10 times faster
than using \code{apply(x, MARGIN=1, FUN=medians)} (as of R v2.4.0).
\end{Section}
\begin{Author}\relax
Henrik Bengtsson (\url{http://www.braju.com/R/})
\end{Author}
\begin{SeeAlso}\relax
See \code{rowMeans()} in \code{\LinkA{colSums}{colSums}}().
\end{SeeAlso}
\begin{Examples}
\begin{ExampleCode}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
# Consistency checks
# - - - - - - - - - - - - - - - - - - - - - - - - - - - -
cat("Consistency checks:\n")
for (kk in 1:20) {
  cat("Random test #", kk, "\n", sep="")

  # Simulate data in a matrix of any shape
  nrow <- sample(2000, size=1)
  ncol <- sample(2000, size=1)
  x <- rnorm(nrow*ncol)
  dim(x) <- c(nrow, ncol)

  # Add NAs?
  nas <- sample(c(TRUE,FALSE), size=1)
  if (nas) {
    nna <- sample(nrow*ncol, size=1)
    x[sample(length(x), size=nna)] <- NA
  }

  na.rm <- sample(c(TRUE,FALSE), size=1)
  t1 <- system.time({
    y1 <- rowMedians(x, na.rm=na.rm)
  })
  t2 <- system.time({
    y2 <- apply(x, MARGIN=1, FUN=median, na.rm=na.rm)
  })
  # When all values of 'y2' are NA, 'y2' is logical
  if (is.logical(y2)) y2 <- as.double(y2)
  stopifnot(identical(y1,y2))
  cat(sprintf("rowMedians()/apply(): %.3g\n", (t1/t2)[3]))
}
\end{ExampleCode}
\end{Examples}

