/usr/share/doc/r-cran-matrixstats/tests/rowWeightedMeans.R is in r-cran-matrixstats 0.14.2-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 | library("matrixStats")
set.seed(1)
x <- matrix(rnorm(20), nrow=5, ncol=4)
print(x)
# Non-weighted row averages
xM0 <- rowMeans(x)
xM1 <- rowWeightedMeans(x)
print(xM1)
stopifnot(all.equal(xM1, xM0))
xM2 <- colWeightedMeans(t(x))
stopifnot(all.equal(xM2, xM0))
# Weighted row averages (uniform weights)
w <- rep(2.5, ncol(x))
xM1 <- rowWeightedMeans(x, w=w)
print(xM1)
stopifnot(all.equal(xM1, xM0))
xM2 <- colWeightedMeans(t(x), w=w)
stopifnot(all.equal(xM2, xM0))
# Weighted row averages (excluding some columns)
w <- c(1,1,0,1)
xM0 <- rowMeans(x[,(w == 1),drop=FALSE])
xM1 <- rowWeightedMeans(x, w=w)
print(xM1)
stopifnot(all.equal(xM1, xM0))
xM2 <- colWeightedMeans(t(x), w=w)
stopifnot(all.equal(xM2, xM0))
# Weighted row averages (excluding some columns)
w <- c(0,1,0,0)
xM0 <- rowMeans(x[,(w == 1),drop=FALSE])
xM1 <- rowWeightedMeans(x, w=w)
stopifnot(all.equal(xM1, xM0))
xM2 <- colWeightedMeans(t(x), w=w)
stopifnot(all.equal(xM2, xM0))
# Weighted row averages (all zero weights)
w <- c(0,0,0,0)
xM0 <- rowMeans(x[,(w == 1),drop=FALSE])
xM1 <- rowWeightedMeans(x, w=w)
stopifnot(all.equal(xM1, xM0))
xM2 <- colWeightedMeans(t(x), w=w)
stopifnot(all.equal(xM2, xM0))
# Weighted averages by rows and columns
w <- 1:4
xM1 <- rowWeightedMeans(x, w=w)
print(xM1)
xM2 <- colWeightedMeans(t(x), w=w)
stopifnot(all.equal(xM2, xM1))
x[sample(length(x), size=0.3*length(x))] <- NA
print(x)
# Non-weighted row averages with missing values
xM0 <- rowMeans(x, na.rm=TRUE)
xM1 <- rowWeightedMeans(x, na.rm=TRUE)
print(xM1)
stopifnot(all.equal(xM1, xM0))
xM2 <- colWeightedMeans(t(x), na.rm=TRUE)
stopifnot(all.equal(xM2, xM0))
# Weighted row averages with missing values
xM0 <- apply(x, MARGIN=1, FUN=weighted.mean, w=w, na.rm=TRUE)
print(xM0)
xM1 <- rowWeightedMeans(x, w=w, na.rm=TRUE)
print(xM1)
stopifnot(all.equal(xM1, xM0))
xM2 <- colWeightedMeans(t(x), w=w, na.rm=TRUE)
stopifnot(all.equal(xM2, xM0))
# Weighted averages by rows and columns
w <- 1:4
xM1 <- rowWeightedMeans(x, w=w, na.rm=TRUE)
xM2 <- colWeightedMeans(t(x), w=w, na.rm=TRUE)
stopifnot(all.equal(xM2, xM1))
|