[Rcpp-devel] using RInside calls in a subroutine?

Eileen Meyer meyer at rice.edu
Tue Dec 7 19:00:35 CET 2010


I need to call R functions through a C++ subroutine.  The problem is 
that, as many have pointed out, you can't call the RInside environment 
more than once.  So how do I get my subroutine to "know" about R? Can I 
pass something along?  I am not really a C++ programmer, so I apologize 
for my ignorance.  (and THANKS for developing some pretty amazing tools)

Here is an example of what doesn't work.

First, the subroutine:

#include "r_funcs.h"
std::vector< double > ks_test(std::vector< double >x, std::vector< 
double >y, int argc, char *argv[]) {

   SEXP ans;

   R.RInside::assign(x,"x");
   R.RInside::assign(y, "y");

   std::string evalstr = " \
     cat('Running ls()\n'); print(ls());    \
     ks <- ks.test(x,y);            \
     ks$p";

   R.RInside::parseEval(evalstr, ans);
   RcppVector<double> vec(ans);
   std::vector<double> v = vec.stlVector();

   return(v);
}

header file:

#ifndef R_FUNCS_H
#define R_FUNCS_H


#include <RInside.h>
//#include <Rcpp.h>

std::vector< double > ks_test(std::vector< double >x, std::vector< 
double >y, int argc, char *argv[]);

#endif //R_FUNCS_H


the main file:

#include <stdio.h>
#include "r_funcs.h"

int main(int argc, char *argv[]) {

   RInside::RInside R(argc,argv);
   // testing stuff
   std::vector< double > x(5);
   std::vector< double > y(5);
   int i;
   double var[5] = {1,2.2,3.4,4.33,42.4};
   for(i=0; i<5; i++) {
     x[i] = var[i];
     std::cout << x[i] << std::endl;
   }

   double var2[5] = {3.224,4.1,4.22,4,4.4};
   for(i=0; i<5; i++) {
     y[i] = var2[i];
   }

   // correct function call
   std::vector< double > v = ks_test(x,y,argc,argv);

   // output
   std::cout << "In main_stat_compare, ks p-value is " << v[0] << std::endl;

   exit(0);
}


Of course if I move the RInside declaration into the subroutine, this 
example works, but I can only call the ks test once. :(








-- 
----------------------------------------
Eileen Meyer

Physics&   Astronomy MS-108
Rice University
6100 Main St. Houston, TX 77005
www.interfolio.com/portfolio/eileenmeyer



More information about the Rcpp-devel mailing list