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

前端 未结 6 846
滥情空心
滥情空心 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:41

    Rserve is another way to get your data from Java to R and back. It is a server which takes R scripts as string inputs. You can use some string parsing and conversion in Java to convert the matrices into strings that can be input into R.

    import org.rosuda.REngine.REXP;
    import org.rosuda.REngine.Rserve.RConnection;
    
    
    public class RtestScript {
    
    private String emailTestScript = "open <- c('O', 'O', 'N', 'N', 'O', 'O', 'N', 'N', 'N', 'O', " +
            " 'O', 'N', 'N', 'O', 'O', 'N', 'N', 'N', 'O');" +
            "testgroup <- c('A', 'A', 'A','A','A','A','A','A','A','A', 'B'," +
            "'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B');" +
            "emailTest <- data.frame(open, testgroup);" +
            "emailTable<- table(emailTest$open, emailTest$testgroup);" +
            "emailResults<- prop.test(emailTable, correct=FALSE);" +
            "print(emailResults$p.value);";
    
    public void executeRscript() {
        try {
            //Make sure to type in library(Rserve); Rserve() in Rstudio before running this
            RConnection testConnection = new RConnection();
    
            REXP testExpression = testConnection.eval(emailTestScript);
            System.out.println("P value: " + testExpression.asString());
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    }
    

    Here is some more information on Rserve. Incidentally, this is also how Tableau can communicate with R as well with their R connection.

    https://cran.r-project.org/web/packages/Rserve/index.html

提交回复
热议问题