0

Is there a way to call an r script from C++ ?

I have an rscript , for example:

myScript.R:

runif(100)

I want to execute this script from C++ and pass the result.

I tried:

#include <Rcpp.h>
#include <iostream>
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector loadFile(CharacterVector inFile){
    NumericVector one = system(inFile);
    return one;
}

inFile : "C:/Program Files/R/R-3.4.2/bin/x64/Rscript C:/Rscripts/myScript.R"

but it gives me :

cannot convert Rcpp::CharacterVector (aka Rcpp::Vector<16>} to const char* for argument 1 to int system(const char*)

George
  • 5,808
  • 15
  • 83
  • 160
  • This won't work, since [system in C++](http://en.cppreference.com/w/cpp/utility/program/system) expects a pointer to `char` and returns an `int` which is typically a status code and not the content of the processes `STDOUT`. What are you trying to achieve? – Ralf Stubner Jun 05 '18 at 09:08
  • @RalfStubner:I want to execute some scripts , get the results and do some calculations.Is there a way to do that?Thanks. – George Jun 05 '18 at 09:12
  • See [here](https://stackoverflow.com/questions/478898/how-to-execute-a-command-and-get-output-of-command-within-c-using-posix) for an example how to grab `STDOUT` of the called process. If you change the functions argument to `string`, you can easily convert that to a `char*`. However, I am really wondering why you want to go back to R from within an Rcpp function. – Ralf Stubner Jun 05 '18 at 09:19

1 Answers1

1

Usual convention is to use Rcpp so as to write expensive C++ code in R.

If you would like to invoke an R script from within c++, and then work with the result, one approach would be be to make use of the popen function.

To see how to convert a rcpp character to std::string see Converting element of 'const Rcpp::CharacterVector&' to 'std::string'

Example:

std::string r_execute = "C:/Program Files/R/R-3.4.2/bin/x64/Rscript C:/Rscripts/myScript.R"

FILE *fp = popen(r_execute ,"r");

You should be able to read the result of the operation from the file stream.

JineshEP
  • 738
  • 4
  • 7