首页 > 解决方案 > 如何通过传递参数从 C++ 调用 R 函数

问题描述

我正在尝试从 C++ 程序调用我的 R 函数。

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

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

标签: c++cr

解决方案


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

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

#include <Rcpp.h>
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 函数在 R 中定义,并与它的两个参数一起rtest传递给 C++ 函数。callFunction部分结果来自Rcpp::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 <RInside.h>

int main(int argc, char *argv[]) {
    // define two vectors in C++
    std::vector<double> x({1.23, 2.34, 3.45});
    std::vector<double> 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<double> 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<std::vector<double> >(rtest(x, y));
    std::cout << z[0] << std::endl;
    exit(0);
}

为了编译它,我使用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

推荐阅读