一.实例化R引擎
Rengine engine = new Rengine(null,false,null);
Rengine.versionCheck() //R版本校验,返回true:版本校验通过 返回false:版本校验未通过
engine.waitForR() //R加载校验,返回true:加载成功 返回false:加载失败
engine.end() //结束R,在后续没有调用R的情况下使用,否则R将退出,不能继续使用R。
二.
R返回值 REXP
REXP rexp=engine.eval("R语句") //执行一个R语句并且返回值存在rexp中
rexp.asInt() rexp.asDouble() rexp.asString()//将返回值转换为java中的类型
engine.assign(String name,double d)//定义一个double类型的R变量
三.求n个数最大值的程序
Rengine engine = new Rengine(null,false,null);
int[] arr = new int[]{-1,2,1,-3,5,4,-2};
engine.assign("x",arr);
REXP rexp = engine.eval_r("max(x)");
int max = rexp.asInt();
System.out.println(max);
engine.end();
四.k-means算法
public class rtest {
public static void main(String[] args) throws InterruptedException, IOException {
Rengine re=new Rengine(null,false,null);
boolean isload=re.waitForR();
if(isload==true)System.out.println("R is ready");
re.eval(" a=c(3,3,3,5,3,3,5,7,5,9,6,5,6,7)");
REXP mrex=re.eval("x=matrix(a,byrow=T,nrow=7) ");//生成测试数据矩阵
double[][] matrix=mrex.asDoubleMatrix();
re.eval("t=kmeans(x,2)");//执行k-means算法
REXP center_rex=re.eval("t$centers"); //得到中心
double[][] centers=center_rex.asDoubleMatrix();
REXP cluster_rex=re.eval("t$cluster"); //得到cluster
int[] cluster=cluster_rex.asIntArray();
String yin="\"";
String code="jpeg(file="+yin+"myplot.jpeg"+yin+")";
System.out.print(code);
re.eval(code);//保存图片
re.eval( " plot(x,col=t$cluster)");
re.eval(" points(t$centers,pch=8,col=t$cluster) ");//绘制图片
re.eval("dev.off()");
for(int i=0;i<centers.length;i++)
{
for(int j=0;j<centers[0].length;j++)
{
System.out.print(centers[i][j]+" ");
}
System.out.print('\n');
} System.out.print('\n');
for(int i=0;i<cluster.length;i++)
{
System.out.print(cluster[i]+" ");
}
System.out.print('\n');
char key=(char)System.in.read();
if(key=='0')
{
System.out.print("exit");
re.end();
}
五.注意事项
在实际使用中,最好对R引擎使用单例模式,在使用完之后注意调用re.end方法;