【问题标题】:How to run R script in python using rpy2如何使用 rpy2 在 python 中运行 R 脚本
【发布时间】:2019-09-14 10:23:13
【问题描述】:

我的问题似乎很基本,但即使在 rpy2 文档中我也找不到答案。 我有 *.R 脚本,它接受一个参数作为“file.txt”(我需要传递参数而不是从命令行)。我想在 python 脚本中调用 R 脚本。我的问题是: 如何将参数传递和恢复到 R 脚本? 我的解决方案是: 假设 R 脚本由这一行开始:

df <- read.table(args[1], header=FALSE)
"
 here args[1] should be the file which is not passed from the command line
"
....

现在我在我的 python 脚本中编写一个函数:

from rpy2 import robjects as ro
def run_R(file):
    r = ro.r
    r.source("myR_script.R")
   # how to pass the file argument to
   # the R script and how to
   # recuperate this argument in the R code?

【问题讨论】:

    标签: python r rpy2


    【解决方案1】:

    为什么只使用rpy2 来运行R 脚本?考虑避免使用此接口,而是使用自动化的Rscript.exe 命令行,Python 可以像任何外部可执行文件一样使用内置的subprocess 调用该命令行,即使在传递所需参数时也是如此。

    下面假设您在 PATH 环境变量中有您的 R bin 文件夹以识别Rscript。如果没有,请在 cmd 的第一个参数中添加此可执行文件的完整路径。另外,请务必将文件的完整路径传递给 run_R 方法:

    from subprocess import Popen, PIPE
    
    def run_R(file):
      # COMMAND WITH ARGUMENTS
      cmd = ["Rscript", "myR_script.R", file]
    
      p = Popen(cmd, cwd="/path/to/folder/of/my_script.R/"      
                stdin=PIPE, stdout=PIPE, stderr=PIPE)     
      output, error = p.communicate()
    
      # PRINT R CONSOLE OUTPUT (ERROR OR NOT)
      if p.returncode == 0:            
          print('R OUTPUT:\n {0}'.format(output))            
      else:                
          print('R ERROR:\n {0}'.format(error))
    

    【讨论】:

      【解决方案2】:

      我的问题似乎很基本,但即使在 rpy2 文档上我也找不到答案。

      不过,这可能是一个很好的起点:

      https://rpy2.github.io/doc/v3.0.x/html/robjects_rpackages.html#importing-arbitrary-r-code-as-a-package

      (...)

      df <- read.table(args[1], header=FALSE)
      "
       here args[1] should be the file which is not passed from the command line
      "
      

      当您到达那里时,命令行的参数早已传递给 R(因为此时 R 已经初始化并运行)。文档中上面的链接将是一种相对优雅的解决方法。否则,您总是可以在 R 中创建一个向量 args

      rpy2.robjects.globalenv['args'] = robjects.vectors.StrVector(['my_file.csv'])
      r.source("myR_script.R")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-08-24
        • 2020-08-03
        • 1970-01-01
        • 2018-09-30
        • 2019-11-03
        • 2016-05-11
        • 2018-12-30
        • 1970-01-01
        相关资源
        最近更新 更多