Implementing the apply function in Rcpp

I am trying to implement the apply function in Rcpp while 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);
} 

but I get the error “cannot convert SEXP to dual assignment” on lines 6 and 11. Is there a way to convert the value returned by an arbitrary function to double? There is also a sugar function for the application function.

+3
source share
2 answers

No sugar function for apply. The easiest way to do what you want is to call as<double>, i.e.:

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

You can also insert this into a type that calls for you as, for example:

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 you can:

// [[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. . - ( ++ 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){
+4

"" "", " Rcpp", lapply():

R> src <- '
+   Rcpp::List input(data);
+   Rcpp::Function f(fun);
+   Rcpp::List output(input.size());
+   std::transform(input.begin(), input.end(), output.begin(), f);
+   output.names() = input.names();
+   return output;
+   '
R> cpp_lapply <- cxxfunction(signature(data = "list", fun = "function"),
+    src, plugin = "Rcpp")

, Rcpp, . ...

, f() , .

+2

Source: https://habr.com/ru/post/1692476/


All Articles