HenrikBengtsson / matrixStats

R package: Methods that Apply to Rows and Columns of Matrices (and to Vectors)
https://cran.r-project.org/package=matrixStats
202 stars 33 forks source link

INCONSISTENCY: rowWeightedMads(..., center=...) only works for scalar `center` #42

Open HenrikBengtsson opened 9 years ago

HenrikBengtsson commented 9 years ago

If argument center is passed to rowWeightedMads(), it is passed as is to weightedMad() for each row calculated. That is, it will only work for center=NULL or length(center) == 1. If one tries to pass a vector as one would do with, say, rowMads(), on gets garbage results or an error:

library("matrixStats")

x <- matrix(rnorm(20), nrow=5, ncol=4)
center <- rowMedians(x)

mu0 <- rowMads(x)
mu1 <- rowMads(x, center=center)
stopifnot(identical(mu1, mu0))

mu2 <- rowWeightedMads(x, w=rep(1,ncol(x)))
stopifnot(identical(mu2, mu0))

mu3 <- rowWeightedMads(x, w=rep(1,ncol(x)), center=center)

Error in weightedMedian(x, w = w, na.rm = NA) :
  Argument 'x' and 'w' are of different lengths: 5 != 4
In addition: Warning message:
In x - center :
  longer object length is not a multiple of shorter object length

This problem also occurs for column-wise calculations.

Troubleshooting

This is because center is passed as is via ...:

rowWeightedMads <- function(x, w=NULL, na.rm=FALSE, ...) {
  apply(x, MARGIN=1L, FUN=weightedMad, w=w, na.rm=na.rm, ...)
}
colWeightedMads <- function(x, w=NULL, na.rm=FALSE, ...) {
  apply(x, MARGIN=2L, FUN=weightedMad, w=w, na.rm=na.rm, ...)
}
HenrikBengtsson commented 7 years ago

Update: Next release will give a more informative error message if length(center) > 1.