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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With