R and Java


In this section we'll use rJava to communicate with R.


We'll use the eval method to run R commands. I've knocked up the file for you: Stats.java. Copy it into your Stats.java file. Have a look at it, and compare it with script.r. Note that you may have to alter the file path.

Run the code - to do this you may have to dig around and find the new configuration you set up. In Eclipse, click the down-arrow next to the green "run" button, and select Run configurations... and select the configuration you created (probably New_configuration before pushing Run (having done this once, next time you should just be able to push the run button. Note also that to stop the program, you'll need to push the red "stop" button on the Eclipse Console window.

Two things about this. One, rJava is very very exception shy. It can quite often go wrong, and the only way you'll know is not to print the REXP objects (which are frequently empty when something goes wrong or when it goes right), but to just do some System.out.printlns and see where it fails. To be honest, even that may not be a lot of help as rJava can continue sending commands and getting back nothing after things have gone belly-up - a combination of both sources of info will usually get you there eventually.

Secondly, note that the plot doesn't update with the linear regression data. There are actually some pretty sophisticated ways of taking control of plots in rJava, but this seems like it might be a good opportunity to use last practical's code. Can you get the data appearing on a JFreeChart? The only thing extra you need to know is how to get the double arrays into JFreeChart. Let's have a quick look at that:


The initial data

Our data.addSeries() call last practical took in a 2D double array, so all we have to do is work out how to get our two 1D arrays x1 and y1 into a 2D array:

	double dataArray[][] = new double[2][];
	dataArray[0] = x1;
	dataArray[1] = y1;

The derived data

Tricker is getting our x2 and y2 arrays into plot.setDataset(2, series2), as series2 here is a XYDataset object. Here's the code:

	XYSeries s2 = new XYSeries("Lines");
	for (int i = 0; i < x2.length; i++) {
		s2.add(x2[i],y2[i]);
	}
		
	XYDataset series2 = new  XYSeriesCollection(s2);
	
	plot.setDataset(2, series2); 

Armed with this, give it a go - see if you can get a full program which uses rJava to load the data and make the prediction of the regression line, and then output the results to JFreeChart. If you can get this running, libraries should never scare you again.


You can leave it there if you like; Part Four has some links in it to further information, including a solid introduction to R you are strongly advised to read. However, as an extra-special treat, if you'd first like to see how to do maps in R like this one by Paul Butler: Facebook Friends, Part Four also contains some pointers to a couple of nice tutorials on this which are very simple to get running.