Skip to content

Instantly share code, notes, and snippets.

@pgtwitter
Last active August 29, 2015 14:13
Show Gist options
  • Save pgtwitter/e5b9e53bbad8d22e5a3d to your computer and use it in GitHub Desktop.
Save pgtwitter/e5b9e53bbad8d22e5a3d to your computer and use it in GitHub Desktop.
curve fitting
package rJava;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.Rengine;
public class RSample {
public static void main(String[] args) {
System.out.println("R_HOME:" + System.getenv("R_HOME"));
System.out.println("java.library.path:"
+ System.getProperty("java.library.path"));
Rengine engine = new Rengine(new String[] {
"--no-save"
}, false, null);
try {
String filename = "dist.dat";
engine.eval("data<-read.csv(\"" + filename + "\")");
engine.eval("x<-data[,1]");
engine.eval("y<-data[,2]");
String[] exprs = {
"a*x+b", "a*x^b", "a*b^x"
};
for (String expr : exprs) {
double[] r = func(engine, expr);
String out = expr;
out += (": a=" + r[0]);
out += (", b=" + r[1]);
out += (" (AIC " + r[2] + ")");
System.out.println(out);
}
} finally {
engine.end();
}
}
private static double[] func(Rengine engine, String f) {
engine.eval("result<-nls(y~(" + f + "), start=c(a=1, b=1))");
REXP result0 = engine.eval("summary(result)");
REXP result1 = engine.eval("AIC(result)");
double[] c = ((result0.asVector()).at("parameters")).asDoubleArray();
double[] ret = {
c[0], c[1], result1.asDouble()
};
return ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment