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

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

executing R scripts from golang using Rserve and Roger

问题

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

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

Golang代码:

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

R脚本:

  1. // 简单示例
  2. parse <- function(xx, nx) {
  3. print(xx)
  4. print(nx)
  5. return(nx)
  6. }

第一个参数被赋值为"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

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

R script

  1. //simple
  2. parse &lt;- function(xx, nx) {
  3. print(xx)
  4. print(nx)
  5. return(nx)
  6. }

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

更改为:

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

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

英文:

Change:

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

To:

  1. 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:

确定