Search code examples
rnullrcpp

In Rcpp, how can I use a variable declared as Nullable?


I'm new to Rcpp but proficient in R. I'm trying to write an Rcpp function for which an argument can be entered as NULL. In Rcpp, my understanding is that that means declaring the variable as "Nullable" in the function arguments, testing whether the input object is NULL using .isNotNULL(), and assigning a new variable the value of the original argument (following the directions described here).

When I attempt run the following code, I get an error that says use of undeclared identifier 'x':

// [[Rcpp::export]]
NumericVector test(Nullable<NumericVector> x_) {
  if (x_.isNotNull()) {
    NumericVector x(x_);
  }
//Other stuff happens
  if (x_.isNotNull()) {
    return x;
  } else {
    NumericVector y = NumericVector::create(3);
    return y;
  }
}

The actual function I'm writing uses x downstream in a loop if x_ is found not to be NULL. All the examples of nullable arguments I've seen use the newly assigned variable only within the if statement and not outside it. How can I use x in subsequent code?


Solution

  • You should study local and global variables in C++.

    This works:

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    NumericVector test(Nullable<NumericVector> x_) {
      NumericVector x;
      if (x_.isNotNull()) {
        x = x_;
      }
      //Other stuff happens
      if (x_.isNotNull()) {
        return x;
      } else {
        NumericVector y = NumericVector::create(3);
        return y;
      }
    }
    

    However, I would restructure the code instead and avoid duplicating the if conditions:

    #include <Rcpp.h>
    using namespace Rcpp;
    
    // [[Rcpp::export]]
    NumericVector test(Nullable<NumericVector> x_) {
      NumericVector x;
      if (x_.isNull()) {
        x = NumericVector::create(3);
        return x;
      }
      
      x = x_;
      //Other stuff happens
      return x;
    }