我想将一个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)
}发布于 2017-04-13 12:10:32
而不是像在这里那样直接调用对象-- .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
*/正如Dirk所指出的那样,在这里使用.get()并不是绝对必要的--使用NumericVector x(x_);将调用Nullable<>::operator SEXP()并同样良好地工作。
此外,请在未来更好地格式化您的代码。
https://stackoverflow.com/questions/43388698
复制相似问题