首页 > 解决方案 > RInside 使用来自 R 的参数调用

问题描述

我正在尝试将参数传递给包含 的exe文件RInside,并且该文件是使用make.

通过从这里获得启发的代码。

#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));
                                    ^

x其次,从 R 传递和传递y给这个 c++ 代码(在编译成 exe 之后)而不是在 c++ 代码中声明它们的最佳方式是什么?我应该使用文件吗?


编辑这是尝试使用额外空间时的错误: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

标签: rrcpprinside

解决方案


编译的问题似乎是 Dirk 和我的g++默认为 C++11,而来自 Rtools 的则不是。您可以通过更改方式来解决该问题,CXX并在随附的以下内容CXXFLAGS中进行了定义:GNUmakefileRInside

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 中的所有细节。

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


推荐阅读