2017-04-13 6 views
1

R 함수를 Rcpp로 변환하려고합니다. 간단한 테스트 코드는 다음과 같습니다. 그러나 설정 한 인수를 처리하는 방법을 모르겠습니다. 기본적으로 NULL입니다.Rcpp : Rcpp :: Nullable NumericVector의 크기를 얻는 방법

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

답변

3

.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 

*/ 

으로는 더크 지적, .get()의 사용은 여기에 꼭 필요한 것은 - Nullable<>::operator SEXP()를 호출하고 똑같이 잘 작동합니다 NumericVector x(x_);를 사용하여.


또한 앞으로 더 나은 형식으로 코드를 작성하십시오.

+2

정답과 형식에 대한 정확한 힌트. 이것은 단지 당신이 원하는 크기의 _instantiation_이 부족했다. 나는 실제로 [이 간단한 형태] (https://github.com/aliceyiwang/mvabund/blob/master/src/Rinterface.cpp#L52-L53)를 선호합니다. 'NumericVector'와 다른'SEXP' 호환 타입에서도 똑같이 작동합니다. –