使用Rserve和Roger从Golang执行R脚本。

huangapple go评论100阅读模式
英文:

executing R scripts from golang using Rserve and Roger

问题

如何通过Roger在Golang中使用Rserve执行R脚本中的函数?

如果一个函数不需要参数或只需要一个参数,那么可以正常工作。问题出现在函数需要两个参数的情况下。

Golang代码:

// 使用反引号也可以正常工作
param := "'hello'"
param2 := "'World'"
jsonx, err := rClient.Eval("parse(as.character(" + param + "," + param2 + "))")
if err != nil {
    s := fmt.Sprintf("%s %s", "发生错误:", err.Error())
    log.Println(s)
    return
}

R脚本:

// 简单示例
parse <- function(xx, nx) {
    print(xx)
    print(nx) 
    return(nx)
}

第一个参数被赋值为"hello",但第二个参数会报错,提示Rserve端没有设置默认值。如何在Golang中调用需要两个或更多参数的函数呢?

英文:

how can i execute a function from a R script via Rserve from golang using Roger...

If a function requires no arguments or just one argument, it works fine..
The problem comes when the function take two arguments.

Golang

//using backticks works fine too
param := &quot;&#39;hello&#39;&quot;
param2 := &quot;&#39;World&#39;&quot;
jsonx, err := rClient.Eval(&quot;parse(as.character(&quot; + param + &quot;,&quot; + param2 &quot;))&quot;)
if err != nil {
    s := fmt.Sprintf(&quot;%s %s&quot;, &quot;Error occured : &quot;, err.Error())
    log.Println(s)
    return
}

R script

//simple
parse &lt;- function(xx, nx) {
    print(xx)
    print(nx) 
    return(nx)
}

the first parameter is assigned hello but the second give an error that no default is set from the Rserve side..
How can i call a function that requires two or more parameters from golang

答案1

得分: 0

更改为:

jsonx, err := rClient.Eval("parse(as.character(" + param + "),as.character(" + param2 + "))")

对于像我这样刚开始接触R并与Go集成的人来说,可能会有些困惑。所以我希望这对某人有所帮助。

英文:

Change:

jsonx, err := rClient.Eval(&quot;parse(as.character(&quot; + param + &quot;,&quot; + param2 &quot;))&quot;)

To:

jsonx, err := rClient.Eval(&quot;parse(as.character(&quot; + param + &quot;),as.character(&quot; + param2 + &quot;))&quot;)

For anyone like myself getting into R and integrating with Go, it can be a bit daunting. So I hope this helps someone.

huangapple
  • 本文由 发表于 2017年1月25日 23:46:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41855820.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定