Search code examples
rrcpp

Check boolean/LogicalVector in Rcpp


I write this Rcpp function:

#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;

// [[Rcpp::export]]
void check(Nullable<LogicalVector> group_center = R_NilValue) {
  if (group_center.isNotNull()) {
    if (group_center) {
      Rprintf("true.\n");
    } else {
      Rprintf("false.\n");
    }
  } else{Rprintf("null.\n");}
}

The goal of this function is that: 1) When no input, return "null"; 2) When input TRUE, return "true"; 3) When input FALSE, return"FALSE".

However, when I try this function, I found that input FALSE still give me "TRUE". Screenshot

Can anyone help with this? Thanks!


Solution

  • The nullable object does not itself evaluate to false even if it contains a false value. You need to cast it to a logical vector and test its first element:

    #include <RcppArmadillo.h>
    // [[Rcpp::depends(RcppArmadillo)]]
    using namespace Rcpp;
    using namespace arma;
    
    // [[Rcpp::export]]
    void check(Nullable<LogicalVector> group_center = R_NilValue) {
      if (group_center.isNotNull()) {
        LogicalVector val(group_center);
        if (val[0]) {
          Rprintf("true.\n");
        } else {
          Rprintf("false.\n");
        }
      } else{Rprintf("null.\n");}
    }
    

    Now, after compilation, in R we have:

    check()
    #> null.
    check(TRUE)
    #> true.
    check(FALSE)
    #> false.