【问题标题】:Load Packages into Renjin in Scala or Java在 Scala 或 Java 中将包加载到 Renjin
【发布时间】:2014-05-22 00:01:50
【问题描述】:

我正在运行一个 scala 应用程序,并想使用 Renjin 调用 R 文件并将值从 scala 传递给 R 文件。当我从 scala 加载 R 文件时,找不到 laply 包时出现错误。如果有人能告诉我如何使用 Renjin 将 R 包加载到 scala 中,那就太好了。

下面是我在 scala 中使用 Renjin 调用 R 文件的代码

  1. 使用以下命令复制带有依赖项的 jar 文件

    scala -cp renjin-script-engine-0.7.0-RC6-jar-with-dependencies.jar

  2. 现在 scala 解释器启动了。

    导入 javax.script.; 导入 org.renjin.sexp.;

    val factory = new ScriptEngineManager();

//创建一个R引擎

val engine = factory.getEngineByName("Renjin");

// 评估磁盘上的 R 脚本

engine.eval(new java.io.FileReader("myscript.R"));

在这一步它错误 cont not find function 'lapply'

如何将包添加到仁进。我在哪里添加类路径。

下面是R文件的代码

score.sentiment = function (sentences, pos.words,neg.words, .progress='none')
{
  require(plyr)
  require(stringr)

  scores =  laply(sentences, function(sentence,pos.words,neg.words){

    sentence = gsub('[[:punct:]]','',sentence)
    sentence = gsub('[[:cntrl:]]','',sentence)
    sentence = gsub('\\d+','',sentence)
    sentence = tolower(sentence)

    word.list = str_split(sentence, '\\s+')
    words = unlist(word.list)

    pos.matches = match(words, pos.words)

    neg.matches = match(words, neg.words)

    pos.matches = !is.na(pos.matches)

    neg.matches = !is.na(neg.matches)

    score = sum(pos.matches) - sum (neg.matches)

    return(score)

  },pos.words, neg.words, .progress = .progress)

  scores.df = data.frame(score=scores, text=sentences)

  return(scores.df)

}

问题的第二部分是如何将参数从 scala 控制台传递到这个 R 文件。

例如,这里的句子是一条推文。我想将它从 scala 发送到 R 函数。

【问题讨论】:

    标签: r scala renjin


    【解决方案1】:

    我不相信 plyrstringr 会与 Renjin 一起开箱即用。我还没有检查过,但我认为 plyr 与 GNU R 的 C Api 有相当大的魔力,Renjin 似乎在 stringr 的一些测试函数上choke

    但是,我认为您不需要上述函数中的任何一个包,只需将基本包中的 laply 和 str_split 分别替换为 sapply 和 strsplit 即可。

    一旦你按照上面的方法评估了你的函数定义,你就可以使用 [invokeFunction](http://docs.oracle.com/javase/7/docs/api/javax/script/Invocable.html#invokeFunction(java.lang.String, java.lang.Object...)) 方法从 Scala/Java 调用这个函数:

    ((Invocable)engine).invokeFunction("score.sentiment", 
           "Best pizza EVER!",
           new String[] { "best", "cool" },
           new String[] { "sucks", "awful" });
    

    Renjin 会将字符串数组转换为 StringVector 对象(R 字符对象),但您也可以自己创建 StringVector 对象。

    http://docs.oracle.com/javase/7/docs/api/javax/script/Invocable.html#invokeFunction(java.lang.String, java.lang.Object...)

    【讨论】:

      【解决方案2】:

      我能够使用 jvmr 在 scala 中使用 r 包。下面是一个示例代码。

      package org.scala.rtest
      
      import org.ddahl.jvmr.RInScala
      
      object RIntegration {
          def main(args: Array[String]) {
             val R = RInScala()
             R>"""
                  require(sparkR)
      
                  score.sentiment = function(sentences, pos.words, neg.words, .progress='none')
                      {
                        require(plyr)
                        require(stringr)
      
      
                        scores = laply(sentences, function(sentence, pos.words, neg.words) {
      
                          # clean up sentences with R's regex-driven global substitute, gsub():
      
                          sentence = gsub('[[:punct:]]', '', sentence, ignore.case=T)
      
                          sentence = gsub('[[:cntrl:]]', '', sentence, ignore.case=T)
      
                          sentence = gsub('\\d+', '', sentence, ignore.case=T)
      
                          # and convert to lower case:
      
                          sentence = tolower(sentence)
      
                          # split into words. str_split is in the stringr package
      
                          word.list = str_split(sentence, '\\s+')
      
                          # sometimes a list() is one level of hierarchy too much
      
                          words = unlist(word.list)
      
                          # compare our words to the dictionaries of positive & negative terms
      
                          pos.matches = match(words, pos.words)
                          neg.matches = match(words, neg.words)
      
                          # match() returns the position of the matched term or NA
                          # we just want a TRUE/FALSE:
      
                          pos.matches = !is.na(pos.matches)
      
                          neg.matches = !is.na(neg.matches)
      
                          # and conveniently enough, TRUE/FALSE will be treated as 1/0 by sum():
      
                          score = sum(pos.matches) - sum(neg.matches)
      
                          return(score)
      
                        }, pos.words, neg.words, .progress=.progress )
                        scores.df = data.frame(score=scores, text=sentences)
                        return(scores.df)
                      } 
      
      
             """
      
              R(" x <- scan('positive-words.txt',what='character',comment.char=';')")
              R(" y <- scan('negative-words.txt',what='character',comment.char=';')")
              R(" z <- scan('twitterstream1.txt', what='character' )")
      
              R.eval("df <- score.sentiment(z,x,y)")  
              println(R.capture("df"))
      
              }
      }
      

      希望这对某人有所帮助。

      【讨论】:

        【解决方案3】:

        Java:

        构建一个专门为 renjin 编译的软件包版本。然后使用 maven 或其他构建工具将其添加到您的类路径中。

        查看 Renjin 文档中的介绍了解更多信息:

        http://docs.renjin.org/en/latest/introduction.html#using-cran-packages-in-renjin

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2011-01-29
          • 2017-09-19
          • 2016-01-26
          • 2021-09-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多