3

我正在运行一个 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"));

在这一步,它会出错,找不到函数“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 函数。

4

3 回答 3

1

我不相信plyrstringr会与 Renjin 一起开箱即用。我还没有检查过,但我认为 plyr 与 GNU R 的 C Api 有相当大的魔力,而 Renjin 似乎对stringr的一些测试功能感到窒息。

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

如上所述评估函数定义后,您可以使用 [invokeFunction]( http://docs.oracle.com/javase/7/docs/api/javax/从 Scala/Java 调用此函数脚本/Invocable.html#invokeFunction(java.lang.String , java.lang.Object...)) 方法:

((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...)

于 2014-04-30T10:33:06.620 回答
0

我能够使用 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"))

        }
}

希望这对某人有所帮助。

于 2014-07-03T18:56:05.853 回答
0

爪哇:

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

查看 Renjin 文档中的介绍以获取更多信息:

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

于 2016-05-11T06:27:55.063 回答