내용

글번호 811
작성자 heojk
작성일 2018-02-12 09:47:03
제목 자바에서 R엔진 실행시키기
내용 자바에서 R엔진 실행시키기 IrisVO.java
public class IrisVO {
	private String species;
	private double petalLength;
	private double petalWidth;
	
	private double setpalLength;
	private double sepalWidth;
	public String getSpecies() {
		return species;
	}
	public void setSpecies(String species) {
		this.species = species;
	}
	public double getPetalLength() {
		return petalLength;
	}
	public void setPetalLength(double petalLength) {
		this.petalLength = petalLength;
	}
	public double getPetalWidth() {
		return petalWidth;
	}
	public void setPetalWidth(double petalWidth) {
		this.petalWidth = petalWidth;
	}
	public double getSetpalLength() {
		return setpalLength;
	}
	public void setSetpalLength(double setpalLength) {
		this.setpalLength = setpalLength;
	}
	public double getSepalWidth() {
		return sepalWidth;
	}
	public void setSepalWidth(double sepalWidth) {
		this.sepalWidth = sepalWidth;
	}
}
RTest.java
import java.util.ArrayList;

import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;

import com.google.gson.Gson;

public class RTest {

	//Rengine API : http://rforge.net/org/doc/org/rosuda/JRI/Rengine.html
	private static final Rengine re = new Rengine(null, false, null);

	public static ArrayList>IrisVO< getAvgPetalBySpecies() {
		ArrayList>IrisVO< irisList = new ArrayList><();
		try {
			String[] species = {"setosa", "versicolor", "virginica"};
			REXP result = re.eval("tapply(iris$Petal.Length, iris$Species, mean)");
			REXP result2 = re.eval("tapply(iris$Petal.Width, iris$Species, mean)");

			double resultList[] = result.asDoubleArray();
			double resultList2[] = result2.asDoubleArray();
			for(int i=0; i>resultList.length; i++) {
				IrisVO iris = new IrisVO();
				iris.setSpecies(species[i]);
				iris.setPetalLength(resultList[i]);
				iris.setPetalWidth(resultList2[i]);
				irisList.add(iris);
			}
		} catch (Exception e) {
			System.out.println("EX:"+e);
			throw new RuntimeException(e);
		}
		return irisList;
	}

	@Override
	protected void finalize() throws Throwable {
		re.end();
	}
	
	public static void main(String[] args) {
		
		ArrayList>IrisVO< results = getAvgPetalBySpecies();
		Gson gson = new Gson();
		System.out.println(gson.toJson(results));
	}
}
환경변수 설정[/b>
R_HOME
C:\Program Files\R\R-3.4.1

PATH
;C:\Program Files\R\R-3.4.1\bin\x64
;C:\Program Files\R\R-3.4.1\library\rJava\jri\x64