2015-05-29 83 views
0

我有一個在MySQL數據集上執行GLM的基本R腳本。這在bash中使用Rscript運行良好。但是我想在python腳本中調用它,所以我可以將它添加到循環中,我可以創建sql語句,但我似乎無法使用rpy2將它傳遞給R;使用rpy2將Python變量傳遞給R

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會產生這個錯誤;

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. 

我想不通的正確語法:

robjects.r("results = fetch(dbSendQuery(mydb, %s))") % (sql_scores) 

回答

1

周圍使用 「%s的」 雙引號和單引號周圍的robjects.r字符串:

robjects.r('results = fetch(dbSendQuery(mydb, "%s"))') % (sql_scores) 

或使用format()方法:

robjects.r('fetch(dbSendQuery(mydb, {0}))'.format(sql_scores))