Last data update: 2014.03.03

R: Calculates the weighted medians for each row (column) in a...
rowWeightedMediansR Documentation

Calculates the weighted medians for each row (column) in a matrix

Description

Calculates the weighted medians for each row (column) in a matrix.

Usage

 rowWeightedMedians(x, w=NULL, rows=NULL, cols=NULL, na.rm=FALSE, ...)
 colWeightedMedians(x, w=NULL, rows=NULL, cols=NULL, na.rm=FALSE, ...)

Arguments

x

A numeric NxK matrix.

w

A numeric vector of length K (N).

rows, cols

A vector indicating subset of rows (and/or columns) to operate over. If NULL, no subsetting is done.

na.rm

If TRUE, missing values are excluded from the calculation, otherwise not.

...

Additional arguments passed to weightedMedian().

Details

The implementations of these methods are optimized for both speed and memory. If no weights are given, the corresponding rowMedians()/colMedians() is used.

Value

Returns a numeric vector of length N (K).

Author(s)

Henrik Bengtsson

See Also

See rowMedians() and colMedians() for non-weighted medians. Internally, weightedMedian() is used.

Examples

 x <- matrix(rnorm(20), nrow=5, ncol=4)
print(x)

# Non-weighted row averages
xM0 <- rowMedians(x)
xM <- rowWeightedMedians(x)
stopifnot(all.equal(xM, xM0))

# Weighted row averages (uniform weights)
w <- rep(2.5, ncol(x))
xM <- rowWeightedMedians(x, w=w)
stopifnot(all.equal(xM, xM0))

# Weighted row averages (excluding some columns)
w <- c(1,1,0,1)
xM0 <- rowMedians(x[,(w == 1),drop=FALSE]);
xM <- rowWeightedMedians(x, w=w)
stopifnot(all.equal(xM, xM0))

# Weighted row averages (excluding some columns)
w <- c(0,1,0,0)
xM0 <- rowMedians(x[,(w == 1),drop=FALSE]);
xM <- rowWeightedMedians(x, w=w)
stopifnot(all.equal(xM, xM0))

# Weighted averages by rows and columns
w <- 1:4
xM1 <- rowWeightedMedians(x, w=w)
xM2 <- colWeightedMedians(t(x), w=w)
stopifnot(all.equal(xM2, xM1))

Results