簡體   English   中英

如何通過C ++調用R函數並傳遞參數

[英]How to call a R function from C++ with passing the parameters

我正在嘗試從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中尋找類似的方法。但是沒有得到結果。 這可能很簡單。 任何幫助表示贊賞。

這個問題有多種解釋,這就是為什么我之前沒有嘗試回答。 這里有幾種可能的解釋的解決方案:

用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函數rtest在R中定義,並與它的兩個參數一起傳遞給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中的示例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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM