我有一个cppFunction矢量ints作为输入,例如:
library(Rcpp)
cppFunction('double test2(NumericVector ints) {
return 42;
}')
Run Code Online (Sandbox Code Playgroud)
如果传递长度至少为1的向量,则输出正确:
> test2(1)
[1] 42
> test2(1:10)
[1] 42
Run Code Online (Sandbox Code Playgroud)
对于长度为0的输入,我得到:
> test2(c())
Error: not compatible with requested type
Run Code Online (Sandbox Code Playgroud)
有没有办法将长度为0或更大的向量传递给我的函数?即我的预期输出是:
> test2_expectedoutput(c())
[1] 42
Run Code Online (Sandbox Code Playgroud)
我知道我可以通过首先检入R并调用函数的不同版本来控制R,但是我想避免这种情况.我希望有一些简单的解决方案,因为在cpp内我也可以有一个NumericVector长度为0,如果我正确理解是什么NumericVector zero;.唯一相关的问题我能找到的这个关于如何从RCPP功能R内部返回NULL对象.
几个月前,我们添加了传递的能力,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)
*/
Run Code Online (Sandbox Code Playgroud)
及其输出:
R> sourceCpp("/tmp/null.cpp")
R> checkNull(1:3)
Sum is 6
[1] TRUE
R> checkNull(NULL)
Nothing to see
[1] FALSE
R>
Run Code Online (Sandbox Code Playgroud)
通过模仿,我们尊重预期的类型,但明确区分存在与否.