在Rcpp中实现Apply功能 [英] implementing apply function in Rcpp

查看:45
本文介绍了在Rcpp中实现Apply功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

到目前为止,我一直在尝试在Rcpp中实现apply函数,代码看起来像这样

I have been trying to implement apply function in Rcpp so far the code looks like this

//[[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?应用功能也有糖功能.

but i'm getting an error "cannot convert SEXP to double in assignment" in line 6 and 11. Is there any way to convert the value returned by an arbitrary function to double? also is there a sugar function for the apply function.

推荐答案

apply 没有糖功能.做您想做的最简单的方法是将 as< double> 称为,即:

There is no sugar function for apply. The easiest way of doing what you want is to call as<double>, i.e.:

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

您还可以将其嵌入一种可以为您调用 as 的类型,例如:

You could also embed this in a type that would call as for you, something like:

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

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

private:
  Function f ;
} ;

以便您可以执行以下操作:

so that you could do:

// [[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中表示):

The F template from above assumes that the function takes a NumericVector and returns something that can be converted to a double. You could also embed type information about both inputs and outputs. Something like this (expressed in 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){

这篇关于在Rcpp中实现Apply功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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