Skip to content

Instantly share code, notes, and snippets.

@pgtwitter
Last active August 29, 2015 14:13
Show Gist options
  • Save pgtwitter/51d0534c516326ad6d10 to your computer and use it in GitHub Desktop.
Save pgtwitter/51d0534c516326ad6d10 to your computer and use it in GitHub Desktop.
frequency table
package rJava;
import java.util.Vector;
import org.rosuda.JRI.REXP;
import org.rosuda.JRI.RVector;
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 {
int n = 1000000;
int m = 10;
double r = 6.0;
double[] x = new double[n];
for (int i = 0; i < n; i++) {
x[i] = 0.0;
for (int j = 0; j < m; j++) {
x[i] += Math.random() * r;
}
}
double[] b = new double[m + 1];
for (int i = 0; i < m + 1; i++) {
b[i] = r * i;
}
engine.assign("x", x);
engine.assign("b", b);
engine.eval("x2<-cut(x, breaks=b, right=FALSE, ordered_result=TRUE)");
engine.eval("x3<-table(x2)");
REXP result = engine.eval("as.data.frame(rbind(x3, x3/sum(x3)))");
RVector resultV = result.asVector();
@SuppressWarnings("unchecked")
Vector<String> labels = (Vector<String>) resultV.getNames();
for (String label : labels) {
double[] v = resultV.at(label).asDoubleArray();
String out = "label=" + label;
out += "\tfreq=" + v[0];
out += "\tratio=" + v[1];
System.out.println(out);
}
String[] sigma1 = {
"[24,30)", "[30,36)"
};
System.out.println("sigma1=" + func(resultV, sigma1));
String[] sigma2 = {
"[18,24)", "[24,30)", "[30,36)", "[36,42)"
};
System.out.println("sigma2=" + func(resultV, sigma2));
String[] sigma3 = {
"[12,18)", "[18,24)", "[24,30)", "[30,36)", "[36,42)",
"[42,48)"
};
System.out.println("sigma3=" + func(resultV, sigma3));
} finally {
engine.end();
}
}
private static double func(RVector resultV, String[] labels) {
double ratio = 0.0;
for (String label : labels) {
ratio += resultV.at(label).asDoubleArray()[1];
}
return ratio;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment