Rcpp:如何获取 Rcpp::Nullable NumericVector 的大小

ear*_*ate 2 rcpp

我想将R函数翻译成Rcpp,一个简单的测试代码如下,但我不知道如何处理默认设置为NULL的参数。

test<- function(t=NULL,tmax=NULL,tmin=NULL){
  if(is.null(t)){
    yout=(tmax-tmin)*(tmin+tmax)
  }else{
    yout=2*t
  }
  return(yout)
}

test(tmax=1:3,tmin=0:2)




  // [[Rcpp::export]]
    NumericVector cpptest(Rcpp::Nullable<Rcpp::NumericVector> t=R_NilValue,
                          Rcpp::Nullable<Rcpp::NumericVector> tmax=R_NilValue,
                          Rcpp::Nullable<Rcpp::NumericVector> tmin=R_NilValue){
      int N=0;
      if(t.isNotNull()) {
        N=t.size(); /* which show a error*/
      }else{
        N=tmax.size(); /* which show a error*/
      }
      NumericVector yout=NumericVector(N);

      if(t.isNotNull()) {
        for(i=0;i<N,i++){
          yout[i]=2*t[i]
        }
      }else{
        for(i=0;i<N,i++){
          yout[i]=(tmax[i]-tmin[i])*(tmin[i]+tmax[i])
        }
      }
      return(yout)
    }
Run Code Online (Sandbox Code Playgroud)

nru*_*ell 5

您需要将其强制转换为基础类型,而不是像.size()您在这里所做的那样直接调用对象。N = t.size();例如,

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
int nullable_size(Nullable<NumericVector> x_ = R_NilValue)
{
    if (x_.isNotNull()) {
        NumericVector x(x_.get());
        return x.size();
    }
    warning("argument x_ is NULL");
    return -1;
}

/*** R

nullable_size(rnorm(5))
# [1] 5

nullable_size(NULL)
# [1] -1
# Warning message:
# In .Primitive(".Call")(<pointer: 0x000000006aa417a0>, x_) :
#   argument x_ is NULL

*/
Run Code Online (Sandbox Code Playgroud)

正如德克所指出的,这里的使用.get()并不是绝对必要的——使用NumericVector x(x_);将调用Nullable<>::operator SEXP()并且同样有效。


另外,请将来更好地格式化您的代码。

  • 正确的答案,以及关于格式的非常正确的提示。这只是缺少您想要的变量的_实例化_大小。我实际上更喜欢[这种更简单的形式](https://github.com/aliceyiwang/mvabund/blob/master/src/Rinterface.cpp#L52-L53)。它与“NumericVector”和其他“SEXP”兼容类型的工作方式相同。 (2认同)