Rcpp passes a vector of length 0 (NULL) to the cppunction function

I have cppFunctionwith a vector intsas input, for example:

library(Rcpp)
cppFunction('double test2(NumericVector ints) {
            return 42;
            }')

The result is correct if you skip a vector of at least 1 length:

> test2(1)
[1] 42
> test2(1:10)
[1] 42

To enter a length of 0, however, I get:

> test2(c())
Error: not compatible with requested type

Is there a way to pass a vector of length 0 or more to my function? That is my expected result:

> test2_expectedoutput(c())
[1] 42

I know that I can control this in R by first checking R and calling another version of the function, but would like to avoid this. I expect that there will be some simple solution, since inside cpp I could also have a NumericVectorlength of 0 if I understood correctly what it was doing NumericVector zero;. The only related question that I could find was how on how to return NULL object from Rcpp functions in the R .

+4
2

c() NULL, numeric. test2. 0 numeric:

#check what `c()` does
str(c())
# NULL

# now we try numeric(0)
test2(numeric(0))
#[1] 42

, C, Fortran C++ ; , , . - :

test2Wrapp<-function(x) test2(as.numeric(x))
test2Wrapp(c())
#[1] 42
#This has the benefit to not calling the internal routines in cases where conversion isn't possible
test2Wrapp(iris)
#Error: (list) object cannot be coerced to type 'double'
+4

Nullable<T>, , .

:

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
bool checkNull(Nullable<NumericVector> x) {
  if (x.isNotNull()) {
    // do something
    NumericVector xx(x);
    Rcpp::Rcout << "Sum is " << sum(xx) << std::endl;
    return true;
  } else {
    // do nothing
    Rcpp::Rcout << "Nothing to see" << std::endl;
    return false;
  }
}

/*** R
checkNull(1:3)
checkNull(NULL)
*/

:

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

R> checkNull(1:3)
Sum is 6
[1] TRUE

R> checkNull(NULL)
Nothing to see
[1] FALSE
R> 

, , .

+6

Source: https://habr.com/ru/post/1623736/


All Articles