Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a function from c++ via environment Rcpp

Tags:

r

rcpp

I am considering calling a R function from c++ via environment, but I got an error, here is what I did

#include <Rcpp.h>
using namespace Rcpp;



// [[Rcpp::export]]
NumericVector call(NumericVector x){
  Environment env = Environment::global_env();
  Function f = env["fivenum"];
  NumericVector res = f(x);
  return res;
}

Type call(x), this is what I got,

Error: cannot convert to function

I know I can do it right in another way,

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector callFunction(NumericVector x, Function f) {
    NumericVector res = f(x);
    return res;
}

and type

callFunction(x,fivenum)

But still wondering why first method failed.

like image 338
skyindeer Avatar asked Feb 07 '23 06:02

skyindeer


2 Answers

fivenum function is not defined in the global environment but in the stats package enviroment, so you should get it from that:

...
Environment stats("package:stats"); 
Function f = stats["fivenum"];
...
like image 120
digEmAll Avatar answered Feb 16 '23 04:02

digEmAll


In addition to @digEmAll's answer, I would like to mention a more general approach, which mimics R's packagename::packagefunctionX(...) approach. The advantage is that you don't have to call library("dependend_library"), i.e., in this case, library(stats). That is useful when you call a function from your package, without previously calling library.

// [[Rcpp::export]]
Rcpp::NumericVector five_nums(Rcpp::NumericVector x){
  Rcpp::Environment stats = Rcpp::Environment::namespace_env("stats");
  Rcpp::Function f = stats["fivenum"];
  return Rcpp::NumericVector(f(x));
}

/*** R
 five_nums(stats::rnorm(25, 2, 3))
*/
like image 33
G4lActus Avatar answered Feb 16 '23 04:02

G4lActus