Learn R Programming

matrixStats (version 0.1.5)

rowWeightedMeans.matrix: Calculates the weighted means for each row (column) in a matrix

Description

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

Usage

## S3 method for class 'matrix':
rowWeightedMeans(x, w=NULL, na.rm=FALSE, ...)
 ## S3 method for class 'matrix':
colWeightedMeans(x, w=NULL, na.rm=FALSE, ...)

Arguments

x
w
A numeric vector of length K (N).
na.rm
If TRUE, missing values are excluded from the calculation, otherwise not.
...
Not used.

Value

Details

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

See Also

See rowSums() and colSums() in colSums().

Examples

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

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

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

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

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

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

Run the code above in your browser using DataLab