Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Default NULL parameter Rcpp

I am trying to define a function with a default NULL parameter in Rcpp. Following is an example:

// [[Rcpp::export]]
int test(int a, IntegerVector kfolds = R_NilValue)
{
  if (Rf_isNull(kfolds))
  {
    cout << "NULL" << endl;
  }
  else
  {
    cout << "NOT NULL" << endl;
  }

  return a;
}

But when I run the code:

test(1)

I get the following error:

Error: not compatible with requested type

How can I solve this issue?

like image 348
Nick Avatar asked Dec 10 '15 15:12

Nick


1 Answers

You are in luck. We needed this in mvabund and Rblpapi, and have it since the last (two) Rcpp releases.

So try this:

// [[Rcpp::export]]
int test(int a, Rcpp::Nullable<Rcpp::IntegerVector> kfolds = R_NilValue) {

  if (kfolds.isNotNull()) {
     // ... your code here but note inverted test ...

A nice complete example is here in Rblpapi. You can also set a default value as you did (subject to the usual rules in C++ of all options to the right of this one also having defaults).

Edit: For completeness sake, here is a full example:

#include <Rcpp.h>

// [[Rcpp::export]]
int testfun(Rcpp::Nullable<Rcpp::IntegerVector> kfolds = R_NilValue) {

  if (kfolds.isNotNull()) {
    Rcpp::IntegerVector x(kfolds);
    Rcpp::Rcout << "Not NULL\n";
    Rcpp::Rcout << x << std::endl;
  } else {
    Rcpp::Rcout << "Is NULL\n";
  }
  return(42);
}

/*** R
testfun(NULL)
testfun(c(1L, 3L, 5L))
*/

which generates this output:

R> sourceCpp("/tmp/nick.cpp")

R> testfun(NULL)
Is NULL
[1] 42

R> testfun(c(1L, 3L, 5L))
Not NULL
1 3 5
[1] 42
R> 
like image 145
Dirk Eddelbuettel Avatar answered Oct 31 '22 18:10

Dirk Eddelbuettel