通过传递参数从 python 代码调用 R 函数

911*_*303 3 r python-3.x

rtest = function(input ,output) {
  a <- input
  b <- output 
  outpath <- a+b
  print(a+b)
  return(outpath)
}
Run Code Online (Sandbox Code Playgroud)

我刚刚返回这个 R 代码作为获取两个数字之和的函数。我尝试使用 subprocess 通过传递 2 个数字作为参数来从我的 python 代码运行此函数。但它不返回总和值作为返回输出。你知道在 python3 中通过传递函数参数来实现这一点的方法吗?

我使用子进程的Python代码是:

args=['3','10'] # (i tried to pass aruments like this) 
command="Rscript" 
path2script = '/...path/rtest.R' 
cmd = [command, path2script] +args 
x = subprocess.check_output(cmd, universal_newlines=True) 
print(x)
Run Code Online (Sandbox Code Playgroud)

但 x 返回 ' ' 空值

911*_*303 6

这可以通过 python 中的 rpy2 库轻松完成。

    import rpy2.robjects as ro
    path="specify/path to/ R file"

        def function1(input,output):
            r=ro.r
            r.source(path+"rtest.R")
            p=r.rtest(input,output)
            return p


  a=function1(12,12)   # calling the function with passing arguments
Run Code Online (Sandbox Code Playgroud)

谢谢。