使用 rpy2 从 python 调用 R 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24544190/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:46:26  来源:igfitidea点击:

Calling R script from python using rpy2

pythonrcallrpy2

提问by Efferalgan

I'm very new to rpy2, as well as R.

我对 rpy2 和 R 都很陌生。

I basically have a R script, script.R, which contains functions, such as rfunc(folder). It is located in the same directory as my python script. I want to call it from Python, and then launch one of its functions. I do not need any output from this R function. I know it must be very basic, but I cannot find examples of R script-calling python codes. What I am currently doing, in Python:

我基本上有一个 R 脚本 script.R,其中包含函数,例如 rfunc(folder)。它与我的 python 脚本位于同一目录中。我想从 Python 调用它,然后启动它的功能之一。我不需要这个 R 函数的任何输出。我知道它一定是非常基础的,但是我找不到 R 脚本调用 python 代码的例子。我目前正在做的事情,在 Python 中:

import rpy2.robjects as robjects

def pyFunction(folder):
    #do python stuff 
    r=robjects.r
    r[r.source("script.R")]
    r["rfunc(folder)"]
    #do python stuff

pyFunction(folder)

I am getting an error on the line with source:

我在源代码行中收到错误:

r[r.source("script.R")] File "/usr/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 226, in __getitem__ res = _globalenv.get(item) TypeError: argument 1 must be string, not ListVector

r[r.source("script.R")] File "/usr/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 226, in __getitem__ res = _globalenv.get(item) TypeError: argument 1 must be string, not ListVector

I quite do not understand how the argument I give it is not a string, and I guess the same problem will then happen on the next line, with folderbeing a python string, and not a R thingie.

我很不明白我给它的参数不是一个字符串,我猜同样的问题会发生在下一行,文件夹是一个 python 字符串,而不是一个 R 的东西。

So, how can I properly call my script?

那么,我该如何正确调用我的脚本呢?

采纳答案by CT Zhu

sourceis a rfunction, which runs a rsource file. Therefore in rpy2, we have two ways to call it, either:

source是一个r函数,它运行一个r源文件。因此,在 中rpy2,我们有两种调用方式:

import rpy2.robjects as robjects
r = robjects.r
r['source']('script.R')

or

或者

import rpy2.robjects as robjects
r = robjects.r
r.source('script.R')

r[r.source("script.R")]is a wrong way to do it.

r[r.source("script.R")]是错误的做法。

Same idea may apply to the next line.

同样的想法可能适用于下一行。