c++ - 在 Rcpp 中实现应用功能

标签 c++ rcpp syntactic-sugar

到目前为止,我一直在尝试在 Rcpp 中实现应用函数,代码如下所示

//[[Rcpp::export]]
NumericVector apply(NumericMatrix x,int dim,Function f){
  NumericVector output;
  if(dim==1){
   for(int i=0;i<x.nrow();i++){
     output[i]=f(x(i,_));
   }    
  }
  else if(dim==2){
   for(int i=0;i<x.ncol();i++){
     output[i]=f(x(_,i));
   }
  }
  return(output);
} 

但我在第 6 行和第 11 行收到错误“无法将 SEXP 转换为 double 赋值”。有没有办法将任意函数返回的值转换为 double ?应用函数也有一个糖函数。

最佳答案

apply 没有糖功能.做你想做的最简单的方法是调用 as<double> ,即:

output[i]=as<double>(f(x(i,_)));

您还可以将其嵌入到调用 as 的类型中对你来说,是这样的:

template <typename T>
class F {
public: 
  F( SEXP f_) : f(f_){}

  inline T operator()(NumericVector x){
    return as<T>(f(x)) ;  
  }

private:
  Function f ;
} ;

这样你就可以:

// [[Rcpp::export]]
NumericVector apply_cpp(NumericMatrix x,int dim,F<double> f){
  if(dim==1){
    NumericVector output(x.nrow());
    for(int i=0;i<x.nrow();i++){
      output[i]=f(x(i,_));
    } 
    return output ;
  }
  else {
    NumericVector output(x.ncol());

    for(int i=0;i<x.ncol();i++){
      output[i]=f(x(_,i));
    }  
    return output ;
  }
} 

F上面的模板假定该函数采用 NumericVector并返回可以转换为 double 的东西.您还可以嵌入有关输入和输出的类型信息。像这样的东西(用 C++11 表示):

template <typename T, typename... Args>
class F {
public: 
  F( SEXP f_) : f(f_){}

  inline T operator()(Args... args){
    return as<T>(f(args...)) ;  
  }

private:
  Function f ;
} ;

那么签名会变成:

// [[Rcpp::export]]
NumericVector apply_cpp(NumericMatrix x,int dim,F<double,NumericVector> f){

关于c++ - 在 Rcpp 中实现应用功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23630538/

相关文章:

c++ - 枚举对象名称

r - 我如何确保 R/Rcpp 代码是可重现的 ("distributable")?

c++ - 是否有一种干净(呃)的方式将 CRTP 与可变参数继承混合使用?

c++ - 数据流管理 : Derived Form contains derived Bitmaps

c++ - STL 容器的内存消耗

c++ - 这是参数还是类型?

c++ - 特殊值不能用作 unordered_map 中的键

Rcpp 在 Mac 10.8 上安装失败

rust - 在 Rust 的一行中为多个变量分配一个值?

c - C 中的数组是指针的语法糖吗?