rpy2运行R函数

时间:2016-10-10 07:54:58

标签: python r rpy2

我有一个R功能

 square_num <- function(x) {
     return(x*x)
 }

当我通过rpy2运行时:

from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
string = """
square_num <- function(x) {
     return(x*x)
}    
"""

testy = STAP(string, "testy")

Jack = testy.square_num(10)
print(Jack)

它有效。

当我在R文件中使用该函数并使用

运行它时
from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
with open('Algo.r', 'r') as f:
    string = f.read()

testy = STAP(string, "testy")

Jack = testy.square_num(10)
print(Jack)

我明白了:

Traceback (most recent call last):
  File "Main.py", line 25, in <module>
    testy = STAP(string, "testy")
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/packages.py", line     290,  in __init__
reval(string, env)
  File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/packages.py", line 75, in reval
p = rinterface.parse(string)
rpy2.rinterface.RParsingError

两个实例中的功能相同。我只是将其复制并粘贴到.r文件中?

1 个答案:

答案 0 :(得分:0)

您是否检查了Python变量string的内容?

以下内容应该有效:

from rpy2.robjects.packages import SignatureTranslatedAnonymousPackage as STAP
string = """
square_num <- function(x) {
     return(x*x)
}    
"""

testy = STAP(string, "testy")

Jack = testy.square_num(10)
print(Jack)

with open('algo.R', 'w') as fh_out:
    fh_out.write(string)

with open('algo.R', 'r') as f:
    string_again = f.read()

testy = STAP(string_again, "testy")

Jack = testy.square_num(10)
print(Jack)