Call R from JAVA to get Chi-squared statistic and p-value

前端 未结 6 838
滥情空心
滥情空心 2020-12-19 23:49

I have two 4*4 matrices in JAVA, where one matrix holds observed counts and the other expected counts.

I need an automated way to calculate the p-value from the chi

6条回答
  •  离开以前
    2020-12-20 00:43

    RCaller 2.2 can do what you want to do. Suppose the frequency matrix is given as in your question. The resulted p.value and df variables can be calculated and returned using the code below:

    double[][] data = new double[][]{
            {197.136, 124.32, 63.492, 59.052},
            {124.32, 78.4, 40.04, 37.24},
            {63.492, 40.04, 20.449, 19.019},
            {59.052, 37.24, 19.019, 17.689}
            };
        RCaller caller = new RCaller();
        Globals.detect_current_rscript();
        caller.setRscriptExecutable(Globals.Rscript_current);
        RCode code = new RCode();
    
        code.addDoubleMatrix("mydata", data);
        code.addRCode("result <- chisq.test(mydata)");
        code.addRCode("mylist <- list(pval = result$p.value, df=result$parameter)");
    
        caller.setRCode(code);
        caller.runAndReturnResult("mylist");
    
        double pvalue = caller.getParser().getAsDoubleArray("pval")[0];
        double df = caller.getParser().getAsDoubleArray("df")[0];
        System.out.println("Pvalue is : "+pvalue);
        System.out.println("Df is : "+df);
    

    The output is:

    Pvalue is : 1.0
    Df is : 9.0
    

    You can get the technical details in here

提交回复
热议问题