rowMedians.matrix          package:R.native          R Documentation

Calculates the median for each row in a matrix

Description:

     Calculates the median for each row in a matrix.

Usage:

     ## S3 method for class 'matrix':
     rowMedians(x, na.rm=FALSE, ...)

Arguments:

       x: A 'numeric' 'matrix'.

   na.rm: If 'TRUE', 'NA's are excluded before calculating the medians,
          otherwise not.

     ...: Not use.

Details:

     The main difference between this implementation and the one in
     'Biobase', '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 'Biobase' version uses a
     more generic method to estimate and quantiles, cf. 'rowQ'.

Value:

     Returns a 'double' 'vector' of length equal to number of rows in
     'x'.

Benchmarking:

     As the example shows, this implementation is roughly 3-10 times
     faster than using 'apply(x, MARGIN=1, FUN=medians)' (as of R
     v2.4.0).

Author(s):

     Henrik Bengtsson (<URL: http://www.braju.com/R/>)

See Also:

     See 'rowMeans()' in 'colSums'().

Examples:

     # - - - - - - - - - - - - - - - - - - - - - - - - - - - -
     # 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]))
     }

