RInside call with arguments from R

2019-08-21 04:20发布

问题:

I am trying to pass arguments to an exe file that includes RInside, and that is compiled using make.

By taking this code inspired from 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);
}

I have two concerns:

First, trying make -f Makefile.win soraw give the error below. why is it not working ?

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

Second, what would be the best way to pass x and y to this c++ code (after compiling into an exe) from R instead of declaring them in the c++ code? Should I use files?


EDIT this is the error when trying to comile with an additional space: candidate expects 0 arguments, 1 provided

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

gives

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

EDIT: this is the error I get after modifying these lines in Makefile.win

回答1:

The problem with compilation seems to be that Dirk's and my g++ default to C++11, while the one from Rtools does not. You can fix that by changing the way CXX and CXXFLAGS are defined in the GNUmakefile that comes with RInside:

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)

Alternatively you could remove all the niceties from C++11.

As for how to provide the input data: That really depends whether you want to provide possibly long vectors or not. I would use files for the former case.



标签: r rcpp rinside