使用rpy2将Python变量传递给R [英] Passing a Python variable to R using rpy2
问题描述
我有基本的R脚本,可以对MySQL数据集执行GLM.在bash中使用Rscript可以很好地运行.但是我想在python脚本中调用它,以便可以将其添加到循环中,可以创建sql语句,但似乎无法使用rpy2将其传递给R;
I have basic R script that performs a GLM on a MySQL dataset. This runs fine using Rscript in bash. However I would like to call it within a python script so I can add it to a loop, I can create the sql statement but I can't seem to pass it to R using rpy2;
for word in words:
sql_scores = "select a.article_id, response, score from scores as a join profile as b on a.article_id = b.article_id where response in (1,0) and keyword = '%s';" % (word[0])
robjects.r("library(RMySQL)")
robjects.r("mydb = dbConnect(MySQL(), user='me', password='xxxx', host='aws.host', dbname='mydb')")
robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
robjects.r("model <- glm(response ~ score , data=results, family=binomial)")
robjects.r("summary(model)")
如果我打印sql_scores,则可以直接在MySQL中运行此命令.但是Python会产生此错误;
If I print sql_scores I can run this fine directly in MySQL. However Python produces this error;
Loading required package: DBI
Traceback (most recent call last):
File "keyword_searcher.py", line 30, in <module>
robjects.r("results = fetch(dbSendQuery(mydb, '%s'))") % (sql_scores)
File "/usr/local/lib/python2.7/dist-packages/rpy2/robjects/__init__.py", line 268, in __call__
p = rinterface.parse(string)
ValueError: Error while parsing the string.
我无法确定以下内容的正确语法:
I can't figure out the proper syntax for:
robjects.r("results = fetch(dbSendQuery(mydb, %s))") % (sql_scores)
推荐答案
在"%s"
周围使用双引号,并在robjects.r字符串周围使用单引号:
Use double quotes around the "%s"
and single quotes around the robjects.r string:
robjects.r('results = fetch(dbSendQuery(mydb, "%s"))') % (sql_scores)
或使用format()
方法:
robjects.r('fetch(dbSendQuery(mydb, {0}))'.format(sql_scores))
这篇关于使用rpy2将Python变量传递给R的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!