4

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.

skyindeer
  • 165
  • 2
  • 11
  • 1
    fivenum function is not defined in the global environment but in the stats package... not sure but this should work: `Environment stats("package:stats"); Function f = stats["fivenum"];` – digEmAll Apr 13 '16 at 09:57
  • 1
    Yes ! It works! Thanks a lot! – skyindeer Apr 13 '16 at 10:09

2 Answers2

9

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"];
...
digEmAll
  • 56,430
  • 9
  • 115
  • 140
2

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))
*/
G4lActus
  • 64
  • 7