如何通过传递参数从C ++调用R函数

我试图从C ++程序调用我的R函数。

rtest = function(input ,output) { a <- input b <- output outpath <- a+b print(a+b) return(outpath) } 

这是我的Rfunction。 我需要找到一种通过传递参数从C调用此函数的方法。 通过传递参数从python代码调用R函数 。 这里我做了类似的方法从python调用R。 所以我需要指定R脚本的路径和函数的名称,并且还能够通过python传递参数。 我在C中寻找类似的方式但是没有得到结果。 这可能是一件简单的事情。 任何帮助表示赞赏。

这个问题有多种解释,这就是我之前没有尝试过答案的原因。 这里解决了几种可能的解释:

用Rcpp定义的C ++函数,从R调用并使用用户定义的R函数 。 这是http://gallery.rcpp.org/articles/r-function-from-c++/ :

 #include  using namespace Rcpp; // [[Rcpp::export]] NumericVector callFunction(NumericVector x, NumericVector y, Function f) { NumericVector res = f(x, y); return res; } /*** R set.seed(42) x <- rnorm(1e5) y <- rnorm(1e5) rtest <- function(x, y) { x + y } head(callFunction(x, y, rtest)) head(x + y) */ 

R函数rtest在R中定义,并与它的两个参数一起传递给C ++函数callFunctionRcpp::sourceCpp()部分结果:

 > head(callFunction(x, y, rtest)) [1] 0.95642325 -0.57197358 -1.45084989 -0.18220091 0.07592864 0.56367202 > head(rtest(x, y)) [1] 0.95642325 -0.57197358 -1.45084989 -0.18220091 0.07592864 0.56367202 

在R和C ++中调用函数会得到相同的结果。

使用RInside的C ++程序,它调用C ++中存在的数据的用户定义的R函数。 这里我们有两种可能:将数据传输到R并在那里调用函数或将函数移动到C ++并像上面一样在C ++中调用R函数:

 #include  int main(int argc, char *argv[]) { // define two vectors in C++ std::vector x({1.23, 2.34, 3.45}); std::vector y({2.34, 3.45, 1.23}); // start R RInside R(argc, argv); // define a function in R R.parseEvalQ("rtest <- function(x, y) {x + y}"); // transfer the vectors to R R["x"] = x; R["y"] = y; // call the function in R and return the result std::vector z = R.parseEval("rtest(x, y)"); std::cout << z[0] << std::endl; // move R function to C++ Rcpp::Function rtest((SEXP) R.parseEval("rtest")); // call the R function from C++ z = Rcpp::as>(rtest(x, y)); std::cout << z[0] << std::endl; exit(0); } 

为了编译它,我使用的是RInside中的示例附带的RInside 。 结果:

 $ make -k run ccache g++ -I/usr/share/R/include -I/usr/local/lib/R/site-library/Rcpp/include -I/usr/local/lib/R/site-library/RInside/include -g -O2 -fdebug-prefix-map=/home/jranke/git/r-backports/stretch/r-base-3.5.0=. -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -g -Wno-ignored-attributes -Wall call_function.cpp -Wl,--export-dynamic -fopenmp -Wl,-z,relro -L/usr/lib/R/lib -lR -lpcre -llzma -lbz2 -lz -lrt -ldl -lm -licuuc -licui18n -lblas -llapack -L/usr/local/lib/R/site-library/RInside/lib -lRInside -Wl,-rpath,/usr/local/lib/R/site-library/RInside/lib -o call_function Running call_function: 3.57 3.57