Skip to content

Rcpp::table handles NAs inconsistently #86

Description

@kevinushey

E.g.

#include <Rcpp.h>
using namespace Rcpp;

template <typename T>
inline IntegerVector do_counts(const T& x) {
  return table(x);
}

// [[Rcpp::export]]
IntegerVector counts(SEXP x) {
  switch (TYPEOF(x)) {
  case INTSXP: return do_counts<IntegerVector>(x);
  case REALSXP: return do_counts<NumericVector>(x);
  case STRSXP: return do_counts<CharacterVector>(x);
  case LGLSXP: return do_counts<LogicalVector>(x);
  default: {
    stop("Unrecognized SEXP type");
    return R_NilValue;
  }
  }
}

/*** R
set.seed(123)
x_num <- rnorm(5)
x_num[ sample(1:length(x_num), 2) ] <- NA
print(x_num)
x_int <- as.integer( round(x_num) )
x_char <- as.character(x_int)
x_lgl <- x_num > 0

counts(x_num)
counts(x_int)
counts(x_char)
counts(x_lgl)
*/

gives me

> set.seed(123)

> x_num <- rnorm(5)

> x_num[ sample(1:length(x_num), 2) ] <- NA

> print(x_num)
[1] -0.56047565          NA  1.55870831  0.07050839          NA

> x_int <- as.integer( round(x_num) )

> x_char <- as.character(x_int)

> x_lgl <- x_num > 0

> counts(x_num)
-0.560476  0.070508  1.558708 
        2         2         1 

> counts(x_int)
<NA>   -1    0    2 
   2    1    1    1 

> counts(x_char)
  -1    0    2 <NA> 
   1    1    1    2 

> counts(x_lgl)
 <NA> FALSE  TRUE 
    2     1     2 

Two things:

  1. The output for numeric case is wrong,
  2. The location of the NA element is different between integer and character. (not such a big problem, but might be worth standardizing)

As far as I can see, table works fine in all the cases where there are no 'special' values (NA, NaN, Inf, -Inf) for numerics.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions