R/rowWeightedMeans.R
rowWeightedMeans.RdCalculates the weighted means for each row (column) in a matrix.
rowWeightedMeans(x, w = NULL, rows = NULL, cols = NULL, na.rm = FALSE,
..., useNames = TRUE)
colWeightedMeans(x, w = NULL, rows = NULL, cols = NULL, na.rm = FALSE,
..., useNames = TRUE)A vector indicating subset of rows to
operate over. If NULL, no subsetting is done.
A vector indicating subset of columns to
operate over. If NULL, no subsetting is done.
If TRUE, missing values are
excluded.
Not used.
If TRUE (default), names
attributes of the result are set, otherwise not.
The implementations of these methods are optimized for both speed and
memory. If no weights are given, the corresponding
rowMeans()/colMeans() is used.
See rowMeans() and colMeans() in
colSums() for non-weighted means. See also
weighted.mean.
x <- matrix(rnorm(20), nrow = 5, ncol = 4)
print(x)
#> [,1] [,2] [,3] [,4]
#> [1,] -0.8374046 -0.4265004 -0.48647150 2.0085900
#> [2,] -0.7157526 -1.7030952 -0.35303944 -1.8544195
#> [3,] 0.3748210 -1.0414974 -0.06230052 -0.4627144
#> [4,] 2.3833280 0.7687350 1.61961511 1.0431038
#> [5,] -0.4639130 -0.7453204 1.24621141 -0.3038375
# Non-weighted row averages
mu_0 <- rowMeans(x)
mu <- rowWeightedMeans(x)
stopifnot(all.equal(mu, mu_0))
# Weighted row averages (uniform weights)
w <- rep(2.5, times = ncol(x))
mu <- rowWeightedMeans(x, w = w)
stopifnot(all.equal(mu, mu_0))
# Weighted row averages (excluding some columns)
w <- c(1, 1, 0, 1)
mu_0 <- rowMeans(x[, (w == 1), drop = FALSE])
mu <- rowWeightedMeans(x, w = w)
stopifnot(all.equal(mu, mu_0))
# Weighted row averages (excluding some columns)
w <- c(0, 1, 0, 0)
mu_0 <- rowMeans(x[, (w == 1), drop = FALSE])
mu <- rowWeightedMeans(x, w = w)
stopifnot(all.equal(mu, mu_0))
# Weighted averages by rows and columns
w <- 1:4
mu_1 <- rowWeightedMeans(x, w = w)
mu_2 <- colWeightedMeans(t(x), w = w)
stopifnot(all.equal(mu_2, mu_1))