本文介绍了使用rpy2从python调用R脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对rpy2和R都非常陌生。

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

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

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:

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)]
文件 /usr/lib/python2.7/dist-packages/rpy2/robjects/__init__.py,第226行,位于__getitem__
res = _globalenv.get(item)
TypeError:参数1必须为字符串,而不是ListVector

我完全不明白我给它的参数不是字符串,然后我猜也是一样的问题发生在下一行,其中 folder 是python字符串,而不是R东西。

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 folder being a python string, and not a R thingie.

因此,如何正确调用脚本?

So, how can I properly call my script?

推荐答案

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

source is a r function, which runs a r source file. Therefore in rpy2, we have two ways to call it, either:

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

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

r [ r.source( script.R)] 是错误的处理方式。

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

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

Same idea may apply to the next line.

这篇关于使用rpy2从python调用R脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 03:11