带有来自 R 的参数的 RInside 调用

RInside call with arguments from R

我正在尝试将参数传递给包含 RInside 且使用 make.

编译的 exe 文件

here.

中获取灵感的代码
#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);
}

我有两个顾虑:

首先,尝试 make -f Makefile.win soraw 给出以下错误。为什么它不起作用?

soraw.cpp:21:36: error: '>>' should be '> >' within a nested template argument list
     z = Rcpp::as<std::vector<double>>(rtest(x, y));
                                    ^

其次,从 R 将 xy 传递给此 c++ 代码(编译成 exe 后)而不是在 c++ 代码中声明它们的最佳方法是什么?我应该使用文件吗?


EDIT 这是尝试使用额外的 space 时出现的错误:candidate expects 0 arguments, 1 provided

z = Rcpp::as<std::vector<double> >(rtest(x, y));

给予

C:/Rtools/mingw_64/x86_64-w64-mingw32/include/c++/bits/stl_vector.h:264:7: note:   no known conversion for argument 1 from '<brace-enclosed initializer list>' to 'const allocator_type& {aka const std::allocator<double>&}'
C:/Rtools/mingw_64/x86_64-w64-mingw32/include/c++/bits/stl_vector.h:253:7: note: std::vector<_Tp, _Alloc>::vector() [with _Tp = double; _Alloc = std::allocator<double>]
       vector()
       ^
C:/Rtools/mingw_64/x86_64-w64-mingw32/include/c++/bits/stl_vector.h:253:7: note:   candidate expects 0 arguments, 1 provided
make: *** [<builtin>: soorig] Error 1

编辑: 这是我在 Makefile.win

中修改这些行后得到的错误

编译的问题似乎是 Dirk 和我的 g++ 默认为 C++11,而 Rtools 的则没有。您可以通过更改 CXXCXXFLAGSRInside 附带的 GNUmakefile 中定义的方式来解决此问题:

CXX :=      $(shell $(R_HOME)/bin/R CMD config CXX11) $(shell $(R_HOME)/bin/R CMD config CXX11STD)
CPPFLAGS := -Wall $(shell $(R_HOME)/bin/R CMD config CPPFLAGS)
CXXFLAGS := $(RCPPFLAGS) $(RCPPINCL) $(RINSIDEINCL) $(shell $(R_HOME)/bin/R CMD config CXX11FLAGS)

或者,您可以删除 C++11 中的所有细节。

至于如何提供输入数据:这实际上取决于您是否要提供可能很长的向量。对于前一种情况,我会使用文件。