默认NULL参数Rcpp [英] Default NULL parameter Rcpp

查看:119
本文介绍了默认NULL参数Rcpp的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Rcpp中的默认NULL参数定义一个函数.以下是一个示例:

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;
}

但是当我运行代码时:

test(1)

我收到以下错误:

错误:与请求的类型不兼容

Error: not compatible with requested type

我该如何解决这个问题?

How can I solve this issue?

推荐答案

您很幸运.我们在​​ mvabund Rblpapi ,并且自上一(两个)Rcpp版本发布以来就拥有它.

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

所以尝试一下:

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

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

一个很好的完整示例是在Rblpapi中. 您还可以像以前一样设置默认值(要遵循C ++中所有选项右侧的所有选项的常规规则,该选项也具有默认值).

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).

为完整起见,这是一个完整的示例:

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))
*/

生成以下输出:

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

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> 

这篇关于默认NULL参数Rcpp的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆