R/rowWeightedMedians.R
rowWeightedMedians.RdCalculates the weighted medians for each row (column) in a matrix.
rowWeightedMedians(x, w = NULL, rows = NULL, cols = NULL,
na.rm = FALSE, ..., useNames = TRUE)
colWeightedMedians(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.
Additional arguments passed to weightedMedian().
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
rowMedians()/colMedians() is used.
Internally, weightedMedian() is used.
See rowMedians() and colMedians() for non-weighted
medians.
x <- matrix(rnorm(20), nrow = 5, ncol = 4)
print(x)
#> [,1] [,2] [,3] [,4]
#> [1,] -0.6487490 1.7879817 -0.6099912 -1.4171540
#> [2,] -1.8689043 0.8673005 -0.3132811 0.6107810
#> [3,] -1.2069966 0.7025809 -0.9221298 0.2415208
#> [4,] 1.8972581 1.6235322 -0.2564806 1.3039648
#> [5,] -0.2615856 -1.5901587 -2.0828546 -0.3345286
# Non-weighted row averages
mu_0 <- rowMedians(x)
mu <- rowWeightedMedians(x)
stopifnot(all.equal(mu, mu_0))
# Weighted row averages (uniform weights)
w <- rep(2.5, times = ncol(x))
mu <- rowWeightedMedians(x, w = w)
stopifnot(all.equal(mu, mu_0))
# Weighted row averages (excluding some columns)
w <- c(1, 1, 0, 1)
mu_0 <- rowMedians(x[, (w == 1), drop = FALSE])
mu <- rowWeightedMedians(x, w = w)
stopifnot(all.equal(mu, mu_0))
# Weighted row averages (excluding some columns)
w <- c(0, 1, 0, 0)
mu_0 <- rowMedians(x[, (w == 1), drop = FALSE])
mu <- rowWeightedMedians(x, w = w)
stopifnot(all.equal(mu, mu_0))
# Weighted averages by rows and columns
w <- 1:4
mu_1 <- rowWeightedMedians(x, w = w)
mu_2 <- colWeightedMedians(t(x), w = w)
stopifnot(all.equal(mu_2, mu_1))