通过环境Rcpp从c ++调用函数

sky*_*eer 4 r rcpp

我正在考虑通过环境从c ++调用R函数,但是我得到了一个错误,这就是我所做的

#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;
}
Run Code Online (Sandbox Code Playgroud)

打字call(x),这是我得到的,

Error: cannot convert to function
Run Code Online (Sandbox Code Playgroud)

我知道我可以用另一种方式做到

#include <Rcpp.h>

using namespace Rcpp;

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

并输入

callFunction(x,fivenum)
Run Code Online (Sandbox Code Playgroud)

但仍然想知道为什么第一种方法失败.

dig*_*All 8

fivenum函数没有在全局环境中定义,而是在stats包环境中定义,所以你应该从中得到它:

...
Environment stats("package:stats"); 
Function f = stats["fivenum"];
...
Run Code Online (Sandbox Code Playgroud)