Running R script or calling R commands from ImageJ macro



I have an ImageJ macro that computes a chi-squared statistic as an indicator of clustering/self-avoidance. I’d like to convert it into a p-value. I’ve found an R command that generates the stat that I’d like to report (pchisq). When I call the pchisq command in an R script from the Macro Editor, it runs correctly.

Is there a way to use the eval command or something similar in an ImageJ macro to call an R command or an R script? I tried the eval and exec commands, but, couldn’t get them to recognize R. When running the R script from the Macro Editor, the macro recorder will record a command, but, I can’t get it to run from a macro – it just generates an unrecognized command error… the command looks like… run("script:D:\code\my1liner.R");.

Any/all tips appreciated.


ps - This code shows what I was hoping to do:

vals = newArray(4);
vals[0] = 20; vals[1] = 30; vals[2] = 40; vals[3] = 10;

c = getChiSquared(vals);
p = getPfromChiSq(c,1);
print("Results {chisq,p} = {"+c+","+p+"}");

function getPfromChiSq(chisq,df) {
	p = eval("R","pchisq("+chisq+",df="+df+",lower.tail=FALSE)"); // THIS is what I wish I could do...
	return p;
function getChiSquared(myList) {
	m  = myList.length;
	n = 0;
	for (i = 0; i<m; i++) {	n = n + myList[i];	}
	chisq = 0;
	for (i=0; i<m; i++) { chisq = chisq + pow(myList[i] - n/m,2)/(n/m); }
	return chisq;


Hi Jeff,

might it be, that Rserve has the functionality you are looking for?

Have a look here:



Thanks, Stefan. I was able to use the Renjin installed with FIJI. I couldn’t get the eval command to use the R engine. But, I was able to call the javascript engine and then call the R engine from javascript. It’s a little awkward, but, it does let me send a simple command to R and get an answer back.

Here’s an example of what the code ended up looking like:

ret = callRScriptviaJavaScript("3+5");
print ("According to R engine, 3+5 is " + ret);
chisq = 80; df = 63;
ret = callRScriptviaJavaScript("pchisq("+chisq+","+df+",lower.tail=FALSE)");
print ("P-Value for chi-square of " + chisq + " and df of " + df + " = " + ret);

function callRScriptviaJavaScript(script) {
	// Use javascript ability to call direct java commands to load R engine and send command to R
	// Note that anything because this is an ImageJ macro calling a javascript calling R...
	//	pretty much anything with quotes in it is likely to fail.
	jscode = "importClass(javax.script.ScriptEngineManager); ";
	jscode = jscode + "sEM = new ScriptEngineManager();";
	jscode = jscode + "engine = sEM.getEngineByName(\"Renjin\");"
	jscode = jscode + "engine.eval(\""+script+"\")";
	ret = eval("script",jscode);
	return ret;