5

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.

1
  • 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"]; Commented Apr 13, 2016 at 9:57

2 Answers 2

10

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"];
...
Sign up to request clarification or add additional context in comments.

Comments

4

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))
*/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.