Calling R from Processing

Nikolaus Gradwohl2010-08-10T20:31:01+02:00

Processing is a simple and powerfull programming language to create images, animation and interaction.

R is a powerfull free software environment for statistical computing.

For me this sounds like a perfect match. This is a short howto that shows how these two languages can comunicate with each other.

On the R-Side I use the Rserve extension, which can be installed by calling

install.packages("Rserve")

from within the R environment.

By calling

library(Rserve)
Rserve()

from within the R, you can start a serverprocess that accepts commands on a network socket and can be used by a javaclient to execute R commands.

procesing2r

In the processing sketch we need to add the two jar files of the javaclient that can be downloaded at the Rserve download page http://www.rforge.net/Rserve/files/

just add the jar files to the sketch using "Add file ..." from the "Sketch"-Menu.

Now we can use the REngine class to execute some R code in the server process and ask R to return the calculated data

The following processing sketch ask R for 100 normal distributed randoms and then sort them. Then the data is fetched into an array of doubles and displayed in the draw method.

import org.rosuda.REngine.Rserve.*;
import org.rosuda.REngine.*;

double[] data;

void setup() {
  size(300,300);

  try {
    RConnection c = new RConnection();  
    // generate 100 normal distributed random numbers and then sort them 
    data= c.eval("sort(rnorm(100))").asDoubles();

  } catch ( REXPMismatchException rme ) {
    rme.printStackTrace();

  } catch ( REngineException ree ) {
    ree.printStackTrace();
  }
}

void draw() {
  background(255);
  for( int i = 0; i < data.length; i++) {
    line( i * 3.0, height/2, i* 3.0, height/2 - (float)data[i] * 50 );
  }
}
Tweet This! submit to reddit Digg!   Tags: | 1 comments | no trackbacks

Trackbacks

Comments

Leave a response

  1. Mike 2011-05-31T04:03:39+02:00

    Can this work the other way i.e. have R call Processing as required? I'd like R to do some calculations and then call Processing for some more esoteric displays, but R has to initiate the call.

    P.s.- I 'get' Matlab/R but am just a Java noob (hence Processing) and know nothing really about the 'serve' portion.

Leave a comment