HenrikBengtsson / matrixStats

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

weightedVar() and weightedSd() on single element gives zero (not NA) #73

Closed HenrikBengtsson closed 9 years ago

HenrikBengtsson commented 9 years ago

weightedVar() and weightedSd() on a single element gives zero, but should give NA_real, e.g.

> weightedVar(1)
[1] 0
> weightedSd(1)
[1] 0

versus

> var(1)
[1] NA
> sd(1)
[1] NA

Ditto on zero elements gives correct results;

> weightedVar(double(0))
[1] NA
> weightedVar(integer(0))
[1] NA
> weightedSd(integer(0))
[1] NA
> weightedSd(double(0))
[1] NA

Discovered while adding redundancy tests for Issue #72.

HenrikBengtsson commented 9 years ago

This is due to a cut'n'paste error from weightedMad();

  # Are there any values left to calculate the weighted median of?
  # This is consistent with how stats::mad() works.
  if (n == 0L) {
    return(naValue);
  } else if (n == 1L) {
    zeroValue <- 0;
    storage.mode(zeroValue) <- storage.mode(x);
    return(zeroValue);
  }

It should be:

  if (n <= 1L) return(naValue);