由于任务的需要,最近一直在使用Rserve包将java与R这两大利器结合起来使用。
在利用R文件进行项目开发时,往往要设计自己的函数库。
本人设计的其中一个R函数如下:
#方法6:主题数的计算 ## 由于java的原因不能执行 topicnum.fun <- function(str){ if(str == "现象"){ print("计算开始") dtm <- kefu.phenomenon.dtm #首先选择最佳的topic number startTime=Sys.time() best.model <- lapply(seq(10,100, by=10), function(k){LDA(dtm, k)}) best.model.logLik <- as.data.frame(as.matrix(lapply(best.model, logLik))) best.model.logLik.df <- data.frame(topics=seq(10,100, by=10), LL=as.numeric(as.matrix(best.model.logLik))) topicnum<-best.model.logLik.df[which.max(best.model.logLik.df$LL),] # 记录下当前程序运行的时间点 print(Sys.time() - startTime) print(topicnum) topicnum }else if(str == "原因"){ dtm <- kefu.reason.dtm #首先选择最佳的topic number startTime=Sys.time() best.model <- lapply(seq(10,100, by=10), function(k){LDA(dtm, k)}) best.model.logLik <- as.data.frame(as.matrix(lapply(best.model, logLik))) best.model.logLik.df <- data.frame(topics=seq(10,100, by=10), LL=as.numeric(as.matrix(best.model.logLik))) topicnum<-best.model.logLik.df[which.max(best.model.logLik.df$LL),] # 记录下当前程序运行的时间点 print(Sys.time() - startTime) print(topicnum) topicnum } } |
其中,在java工程中的一个类执行以下程序:
package com.buptshl.r; import org.rosuda.REngine.Rserve.RConnection; import org.rosuda.REngine.Rserve.RserveException; public class TestR08 { public static void main(String[] args) { RConnection rc = null; try { rc = new RConnection(); System.out.println("开始运算"); //加载运算过程中需要的函数库 rc.eval("source(\"E:/tomcat/apache-tomcat-7.0.63/webapps/textmining/text analysis/rsource/test.R\")"); System.out.println("结束运算"); } catch (RserveException e) { e.printStackTrace(); }finally{ rc.close(); } } } |
程序执行时,报错:
经过逐句调试之后,将R程序中if语句的print("计算开始")注释或者删除掉之后。
#方法6:主题数的计算 ## 由于java的原因不能执行 topicnum.fun <- function(str){ if(str == "现象"){ # print("计算开始") dtm <- kefu.phenomenon.dtm #首先选择最佳的topic number startTime=Sys.time() best.model <- lapply(seq(10,100, by=10), function(k){LDA(dtm, k)}) best.model.logLik <- as.data.frame(as.matrix(lapply(best.model, logLik))) best.model.logLik.df <- data.frame(topics=seq(10,100, by=10), LL=as.numeric(as.matrix(best.model.logLik))) topicnum<-best.model.logLik.df[which.max(best.model.logLik.df$LL),] # 记录下当前程序运行的时间点 print(Sys.time() - startTime) print(topicnum) topicnum }else if(str == "原因"){ dtm <- kefu.reason.dtm #首先选择最佳的topic number startTime=Sys.time() best.model <- lapply(seq(10,100, by=10), function(k){LDA(dtm, k)}) best.model.logLik <- as.data.frame(as.matrix(lapply(best.model, logLik))) best.model.logLik.df <- data.frame(topics=seq(10,100, by=10), LL=as.numeric(as.matrix(best.model.logLik))) topicnum<-best.model.logLik.df[which.max(best.model.logLik.df$LL),] # 记录下当前程序运行的时间点 print(Sys.time() - startTime) print(topicnum) topicnum } } |
除此之外,在语句中尽量不要使用stop()或者cat语句,这些都会导致在利用java调用eval函数时报错。这只是个人实践的记录。
欢迎留言