在Scala或Java中将包加载到Renjin中

时间:2014-04-09 01:59:18

标签: r scala renjin

我正在运行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。;     import org.renjin.sexp。;

    val factory = new ScriptEngineManager();

  3. //创建一个R引擎

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

    //评估磁盘上的R脚本

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

    在此步骤中,错误连续找不到功能' lapply'

    如何向Renjin添加包。我在哪里添加类路径。

    以下是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函数。

3 个答案:

答案 0 :(得分:0)

我不相信plyrstringr可与Renjin一起开箱即用。我还没有检查过,但我认为plyr对GNU R的C Api起了很大的作用,Renjin似乎choke对某些字符串的测试函数。

但是,我不认为你在上面的函数中需要任何一个包,只需要从基础包中分别使用sapply和strsplit替换laply和str_split。

如上所述,一旦您评估了函数定义,就可以使用[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 ...)

答案 1 :(得分: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"))

        }
}

希望这对某人有所帮助。

答案 2 :(得分:0)

爪哇:

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

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

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