Nic*_*ick 10 parameters null r rcpp
我正在尝试使用默认NULL
参数定义一个函数Rcpp
.以下是一个例子:
// [[Rcpp::export]]
int test(int a, IntegerVector kfolds = R_NilValue)
{
if (Rf_isNull(kfolds))
{
cout << "NULL" << endl;
}
else
{
cout << "NOT NULL" << endl;
}
return a;
}
Run Code Online (Sandbox Code Playgroud)
但是当我运行代码时:
test(1)
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
错误:与请求的类型不兼容
我该如何解决这个问题?
Dir*_*tel 17
你很幸运.我们需要在mvabund和Rblpapi中使用它,并且自上一次(两次)Rcpp发布以来就有它.
试试这个:
// [[Rcpp::export]]
int test(int a, Rcpp::Nullable<Rcpp::IntegerVector> kfolds = R_NilValue) {
if (kfolds.isNotNull()) {
// ... your code here but note inverted test ...
Run Code Online (Sandbox Code Playgroud)
Rblpapi就是一个很好的完整例子.您也可以像设置一样设置默认值(根据C++中通常的规则,这个规则右边的所有选项也有默认值).
编辑:为了完整起见,这是一个完整的例子:
#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))
*/
Run Code Online (Sandbox Code Playgroud)
生成此输出:
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>
Run Code Online (Sandbox Code Playgroud)