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

Description Usage Arguments Details Value Author(s) See Also Examples

Description

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

Usage

1
2
3
4
 ## 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

A numeric NxK matrix.

w

A numeric vector of length K (N).

na.rm

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

...

Not used.

Details

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

Value

Returns a numeric vector of length N (K).

Author(s)

Henrik Bengtsson

See Also

See rowMeans() and colMeans() in colSums() for non-weighted means. See also weighted.mean.

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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))

Example output

           [,1]       [,2]       [,3]       [,4]
[1,] -0.3609804  0.9128517 -0.9427240 -1.8899136
[2,] -0.5507407 -0.5147245 -0.5167359  0.7143086
[3,] -0.4799142  0.9030043  1.0868770  2.7231014
[4,]  0.9605834  0.1443141 -0.8863034 -0.2060908
[5,]  0.9946198  0.1260654 -0.3173565 -0.7276822

matrixStats documentation built on May 2, 2019, 4:52 p.m.