Using the REnvironment

From Jstacs
Jump to navigationJump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.
REnvironment e = null;
try {
	//create a connection to R with YOUR server name, login and password
	e = new REnvironment( server, login, password );

	System.out.println( "java: " + System.getProperty( "java.version" ) );
	System.out.println();
	System.out.println( e.getVersionInformation() );

	// compute something in R
	REXP erg = e.eval( "sin(10)" );
	System.out.println( erg.asDouble() );

	//create a histrgram in R in 3 steps
	//1) create the data
	e.voidEval( "a = 100;" );
	e.voidEval( "n = rnorm(a)" );
	//2) create the plot command
	String plotCmd = "hist(n,breaks=a/5)";
	//3a) plot as pdf
	e.plotToPDF( plotCmd, "./../test.pdf", true );
	//or
	//3b) create an image and show it
	BufferedImage i = e.plot( plotCmd, 640, 480 );
	REnvironment.showImage( "histogramm", i, JFrame.EXIT_ON_CLOSE );

} catch ( Exception ex ) {
	ex.printStackTrace();
} finally {
	if( e != null ) {
		try {
			//close REnvironment correctly
			e.close();
		} catch ( Exception e1 ) {
			System.err.println( "could not close REnvironment." );
			e1.printStackTrace();
		}
	}
}