25.4 Missing values

Missing values behave differently for C++ scalers

  • Scalar NA’s in Cpp : NA_LOGICAL, NA_INTEGER, NA_REAL, NA_STRING.

  • Integers (int) stores R NA’s as the smallest integer. Better to use length 1 IntegerVector

  • Doubles use IEEE 754 NaN , which behaves a bit differently for logical expressions (but ok for math expressions).

evalCpp("NA_REAL || FALSE")
#> [1] TRUE
  • Strings are a class from Rcpp, so they handle missing values fine.

  • bool can only hold two values, so be careful. Consider using vectors of length 1 or coercing to int

25.4.1 Vectors

  • Vectors are all type introduced by RCpp and know how to handle missing values if you use the specific type for that vector.
#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
List missing_sampler() {
  return List::create(
    NumericVector::create(NA_REAL),
    IntegerVector::create(NA_INTEGER),
    LogicalVector::create(NA_LOGICAL),
    CharacterVector::create(NA_STRING)
  );
}
str(missing_sampler())
#> List of 4
#>  $ : num NA
#>  $ : int NA
#>  $ : logi NA
#>  $ : chr NA