0

I'm trying to create a program on Processing that can do some calculations in R with each iteration of the draw part of Processing. These calculations need to be done with a function inside a package I need to load in the Rsession.
I'm using Rserve to connect R with Processing. I used to do the following but it causes to load said library in each iteration.

void draw{ 
  try {
  c.eval("library('png');library('glmnet')");
  }catch ( REXPMismatchException rme ) {
    rme.printStackTrace();
  } catch ( REngineException e ) {
    e.printStackTrace();
}

so instead I tried the following

void setup() {
try {
  RConnection c = new RConnection();
  c.eval("library('png');library('glmnet')");
  } catch ( REngineException e ) {
    e.printStackTrace();
  }
void draw() {
try {
  //calculations using functions from libraries above
  }catch ( REXPMismatchException rme ) {
    rme.printStackTrace();
  } catch ( REngineException e ) {
    e.printStackTrace();
  }
}

But this second approach results in the following error

Cannot find anything called "c"

So I'm guessing the connection doesn't survive after the setup phase. How can I preserve the rconnection using the second structure?

Diego Aguado
  • 1,604
  • 18
  • 36

1 Answers1

0

I don't know anything about R, but the problem here seems to be that your variable goes out of scope. You just have to declare it in a place that gives it scope in both the setup() and draw() functions, namely at the top of your sketch:

RConnection c;

void setup() {
  try {
    c = new RConnection();
    c.eval("library('png');library('glmnet')");
  } 
  catch ( REngineException e ) {
    e.printStackTrace();
  }
}

void draw() {
  try {
    //you can now use your c variable here
  }
  catch ( REXPMismatchException rme ) {
    rme.printStackTrace();
  }
  catch ( REngineException e ) {
    e.printStackTrace();
  }
}

More info about scope in Processing can be found here.

Kevin Workman
  • 41,537
  • 9
  • 68
  • 107