新聞中心
如何在python中調(diào)用r?這其中包括了如何調(diào)用R的對(duì)象(函數(shù)和包),R和python的對(duì)象如何互相轉(zhuǎn)換,以及如何調(diào)用R的腳本(外界參數(shù)的輸入)。python提供了一個(gè)模塊rpy2,可以較好地完成這項(xiàng)工作。

一、安裝rpy2
rpy2的網(wǎng)址:http://rpy.sourceforge.net/index.html
可以使用easy_install安裝,# easy_install rpy2
注意事項(xiàng):
(1)如果是源代碼編譯安裝R,需要在configure步驟加入后綴 --enable-R-shlib。
(2)需要安裝python-devel包。
二、python調(diào)用R對(duì)象
1、使用rpy2.robjects包的r對(duì)象
調(diào)用方法如下,以下robject.r的調(diào)用方法實(shí)際上是開啟了一個(gè)R的交互進(jìn)程,只需要將R的代碼寫入一個(gè)字符串內(nèi)(注1),接著調(diào)用R即可:
import rpy2.robjects as robjects
此時(shí),有三種方法調(diào)用R對(duì)象:
第一種:robjects.r['pi']
第二種:robjects.r('pi')(這種方法從某種程度上講是萬能的,因?yàn)榭梢詫⑷我獯笮『烷L(zhǎng)度的R代碼寫成一個(gè)python字符串,之后通過robjects.r('Rcode')調(diào)用執(zhí)行。)
第三種:robjects.r.pi(這種方法對(duì)于名稱中有“點(diǎn)號(hào)”的變量會(huì)出問題,比如data.frame/read.csv等,所以推薦使用第一種方法)
相關(guān)推薦:《Python教程》
以下是一個(gè)創(chuàng)建和使用R函數(shù)(自己創(chuàng)建的函數(shù)或者R內(nèi)置函數(shù))。注意:最后一種方法,對(duì)于對(duì)付一些特殊的格式很管用:
# creat an R function
>>> robjects.r(
'''
f <- function(r){pi * r}
. '''
)
>>> robjects.r['f'](3)
[9.424778]
# internal function in R
>>> robjects.r['ls']()
# another internal function
>>> l = robjects.r['letters']
>>> len(l)
>>> robjects.r['paste'](l, collapse = '-')
# an alternative way of getting 'paste' function in R
# eval the R code
>>> coder = 'paste(%s, collapse = "-")' % (l.r_repr())
>>> robjects.r(coder)
對(duì)于一些特殊的R對(duì)象比如list和matrix,如果python要調(diào)去其中的部分?jǐn)?shù)據(jù),可以通過其rx()和rx2()方法操作。對(duì)于list,可以查看其name屬性,以獲得列表個(gè)個(gè)元素名稱。rx()和相當(dāng)于"["操作(注意取出的是R的list對(duì)象),而rx2()相當(dāng)于"[["操作。一個(gè)例子:
>>> tmp = r("list(a = matrix(1:10, nrow = 2), b = 'Hello')")
>>> print tmp
$a
[,1] [,2] [,3] [,4] [,5]
[1,] 1 3 5 7 9
[2,] 2 4 6 8 10
$b
[1] "Hello"
>>> tmp.names
['a', 'b']
>>> tmp.rx('a')
[Matrix]
a:
[ 1, 2, 3, ..., 8, 9, 10]
>>> tmp.rx(1)
[Matrix]
a:
[ 1, 2, 3, ..., 8, 9, 10]
>>> tmp.rx2(1)
[ 1, 2, 3, ..., 8, 9, 10]
>>> tmp.rx2('a').rx(1, 1) # first element of 'a'
[ 1]
>>> tmp.rx2('a').rx(1, True) # first row of 'a'
[ 1, 3, 5, 7, 9]
注意事項(xiàng):
如果函數(shù)有警告(warnings),在ipython等IDE上能夠執(zhí)行,但是如果是腳本或者與網(wǎng)頁服務(wù)器交互,則會(huì)產(chǎn)生錯(cuò)誤。
解決辦法:
(1)魯莽的解決很簡(jiǎn)單,強(qiáng)行忽略R的警告,options(warn = -1)或者R代碼放入函數(shù)中suppressWarnings()。
(2)第二種辦法,如果是自己代碼中使用了warning()函數(shù),則將warning信息換成字符串,之后單獨(dú)輸出。
如果R的函數(shù)參數(shù)用到向量,有兩種解決辦法:
(1)使用robject.**Vector()函數(shù)(見下)先將python對(duì)象轉(zhuǎn)換成R對(duì)象,然后帶入函數(shù);
(2)直接使用python對(duì)象,一個(gè)例子:
>>> from rpy2.robjects import r >>> a = r['matrix'](range(10), nrow = 2) >>> print a [,1] [,2] [,3] [,4] [,5] [1,] 0 2 4 6 8 [2,] 1 3 5 7 9
2、python對(duì)象轉(zhuǎn)換成R對(duì)象
通常,可以將python的list對(duì)象,轉(zhuǎn)換成為R的vector對(duì)象,之后直接使用R函數(shù)調(diào)用。相應(yīng)的函數(shù)是robjects.StrVector()/robjects.IntVector()/robjects.FloatVector()/robjects.complexVector()/robjects.FactorVector()/robjects.BoolVector()/,這些函數(shù)將python列表轉(zhuǎn)化成R的字符/整數(shù)/浮點(diǎn)/復(fù)數(shù)/因子/布爾向量。robjects.ListVector()將python的字典轉(zhuǎn)換成R的列表。
具體轉(zhuǎn)換可見http://rpy.sourceforge.net/rpy2/doc-2.2/html/vector.html#creating-vectors
比如:
>>> testmatrix = robjects.IntVector([1, 2, 3, 4])
>>> robjects.r['matrix'](testmatrix, nrow = 2)
# another dynamic arguments example
>>> x = robjects.IntVector(range(10))
>>> y = robjects.r.rnorm(10)
>>> kwargs = {'ylab': 'foo/bar', 'type': 'b', 'col': 'blue', 'log': 'x'}
>>> robjects.r.plot(*args, **kwargs)
>>>
注意事項(xiàng):
使用vector系列函數(shù)時(shí),輸入的只能是python的列表,而不能是數(shù)字或者字符串。
3、載入和使用R包
使用rpy2.robjects.packages.importr對(duì)象,調(diào)用方法是
>>> from rpy2.robjects.packages import importr
>>> base = importr('base')
>>> stats = importr('stats')
>>> affy = importr('affy')
>>> stats.rnorm(10)
如果想引用一個(gè)包中的隱變量,也很簡(jiǎn)單,只要載入包,然后所有r命令化成成字符串,之后引用即可(這種方法是萬能的),比如
>>> from rpy2.robjects.packages import importr
>>> importr('hwriter')
>>> a = r('hwriter:::hwrite.table(matrix(1:10, 2))')
>>> print(a)
[1] "| 1 | 3 | 5 | 7 | 9 |
| 2 | 4 | 6 | 8 | 10 |
4、導(dǎo)入R腳本
使用R的source函數(shù):
from rpy2.robjects import r
r.source('testrscript.r')
5、轉(zhuǎn)換R對(duì)象為全局變量
因?yàn)槭褂煤瘮?shù)robjects.globalenv()將對(duì)象轉(zhuǎn)換成全局變量,特別是遇到python找不到一個(gè)R對(duì)象時(shí)(此時(shí)R對(duì)象可能通過r('Rcode')調(diào)用),留意將R對(duì)象轉(zhuǎn)變成全局變量。
三、R對(duì)象轉(zhuǎn)換成python對(duì)象
推薦使用tuple( )或者list( )函數(shù),將R對(duì)象轉(zhuǎn)換成tuple或者list。
>>> a = r('c(1, 2, 3)')
>>> a
[1.000000, 2.000000, 3.000000]
>>> str(a)
'[1] 1 2 3n'
>>> tuple(a)
(1.0, 2.0, 3.0)
>>> list(a)
[1.0, 2.0, 3.0]
>>> b = r('matrix(1:6, 2, 3)')
>>> b
[1,2,3,4,5,6]
>>> print b
[,1] [,2] [,3]
[1,] 1 3 5
[2,] 2 4 6
>>> tuple(b)
(1, 2, 3, 4, 5, 6)
>>> list(b) 當(dāng)前題目:創(chuàng)新互聯(lián)Python教程:python怎么調(diào)用R
網(wǎng)站路徑:http://m.5511xx.com/article/copsjse.html


咨詢
建站咨詢
