0

我正在尝试在处理上创建一个程序,该程序可以在处理的绘制部分的每次迭代中在 R 中进行一些计算。这些计算需要使用我需要在 Rsession 中加载的包内的函数来完成。
我正在使用 Rserve 将 R 与 Processing 连接起来。我曾经做过以下事情,但它会导致在每次迭代中加载所述库。

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

所以我尝试了以下

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();
  }
}

但是第二种方法会导致以下错误

Cannot find anything called "c"

所以我猜测连接在设置阶段后无法生存。如何使用第二种结构保留重新连接?

4

1 回答 1

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.

于 2015-02-18T15:26:31.353 回答