2014-10-04 65 views
0

我正在使用rpy2來運行一些R命令。不要問爲什麼。這是必要的。所以這是代碼的一部分。將R對象插入R代碼字符串

import pandas.rpy.common as com 
from rpy2.robjects import r 

#Load emotionsCART decision tree. Successful. 
r_dataframe = com.convert_to_r_dataframe(data) 
print type(r_dataframe) 
(<class 'rpy2.robjects.vectors.DataFrame'>) 

r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe) 

這裏我想要做的就是將這個r_dataframe傳遞到計算中。我使用之前加載的決策樹預測值。但最後一行給我一個錯誤。它說

Traceback (most recent call last): 
    File "<pyshell#38>", line 1, in <module> 
r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe) 
File "C:\Python27\lib\site-packages\rpy2\robjects\__init__.py", line 245, in __call__ 
    p = rinterface.parse(string) 
    ValueError: Error while parsing the string. 

想法爲什麼會發生這種情況?

+0

如果您正在使用Python和R,您可能需要查看IPython。以下是使用單元魔術的示例:https://gist.github.com/alexwoolford/c77f1fc87e37d8a572e4來回移動數據幀非常簡單。 – 2014-10-04 06:14:24

+0

這將是有用的,但事情是這部分代碼是一個更大的程序的一部分,它又被另一個python程序調用。 ( – nEO 2014-10-04 06:37:21

回答

0

我認爲:

r('pred = predict(emotionsCART, newdata = %s)') %(r_dataframe) 

應該是:

r('pred = predict(emotionsCART, newdata = %s)' % (r_dataframe)) 

%(r_dataframe)是與r()部分相關聯,而應該與''(串)相關聯。

但是,如果沒有可重複的例子,很難檢查。

+0

)嗨,我試過 r('pred = predict(emotionsCART,newdata =%s)'%(r_dataframe)) 嗯,我猜你喜歡拿出ncol 。我的意思是 r('ncol(%s)'%(r_dataframe)) 其中r_dataframe首先使用pd.read_csv讀取,然後將轉換應用到r數據幀函數 – nEO 2014-10-04 06:34:00

+0

另外,我也發現了這個。 ://rpy.sourceforge.net/rpy2/doc-2.1/html/introduction.html#interpolating-r-objects-into-r-code-strings並且它正在工作 – nEO 2014-10-04 06:50:31

+0

如果我的回答解決了您的問題,請接受答案通過點擊我答案左邊的刻度標記,這表明你的問題已經得到了解答, – 2014-10-04 09:52:39