python 與 R 是當今數據分析的兩大主流語言。作為一個統計系的學生,我最早接觸的是R,后來才接觸的python。python是通用編程語言,科學計算、數據分析是其重要的組成部分,但並非全部;而R則更偏重於統計分析,畢竟R是統計學家發明的,本身就是為統計而生。python的優勢在於其全能性,幾乎所有的領域都有python的身影,而R則在統計及其相關領域非常專業。二者各有優勢。那么這么好的兩個東西,能不能結合到一起呢?答案是肯定的。要想實現這種功能,一般必須要提供相應的調用接口。rpy2這個第三方庫就提供了python調用R的接口。本文主要介紹rpy2的簡單使用。
其實,在前一段時間,我就曾經嘗試過安裝rpy2,但是只在linux環境下安裝成功了,在windows下總是安裝失敗。直到最近,我發現了一個非官方的python第三方庫下載網址:
http://www.lfd.uci.edu/~gohlke/pythonlibs。這個網址提供的第三方庫還是比較全的,而且是都是編譯好的.whl文件,各個版本的都有,比如Pymediea,rpy2等比較難找的庫這里都有,所以特此在這里分享給大家。找到rpy2這個庫,由於我的python版本是2.7 64位,所以選擇http://www.lfd.uci.edu/~gohlke/pythonlibs/tuoh5y4k/rpy2-2.7.8-cp27-none-win_amd64.whl這個地址下載。下載完成之后,解壓,將解壓后的全部文件放入python的site-packages目錄下。還要做的一件重要的事情是增加環境變量R_HOME,將其值設置為電腦中R的安裝路徑。設置好了之后,發現 import rpy2 就可以正常導入了。
常用的命令:
1. import rpy2.robjects as robjects 這個命令是導入 r對象
2. robjects.r("r_script") 可以執行r代碼,比如 pi = robjects.r('pi') 就可以得到 R 中的PI(圓周率),返回的變量pi是一個向量,或者理解為python中的列表,通過
pi[0] 就可以取出圓周率的值。
3. robjects.r.source(“file.r”)可以執行r腳本文件。例子如下:
robjects.r.source('plot_demo.r')
plot_demo.r 內容如下:
# R 語言測試腳本 x <- c(1,2,3,4) y <- x*x jpeg(file="plot.jpg") # 保存圖像 plt <- plot(x,y) # 畫散點圖 dev.off() # 關閉設備
運行上面的代碼后,就可以得到一幅名為 plot.jpg的散點圖了。
a = robjects.r('a<-c(1,2,3)') print(a)
運行得到 [1] 1 2 3
x = robjects.r('x') y = robjects.r('y') print(x) print(y)
運行得到:
[1] 1 2 3 4
[1] 1 4 9 16
當然rpy2不僅可以將R的數據對象轉換為python的變量(或對象),還以將python的列表,字典等數據類型轉換為R的向量或數據框類型,對應的函數有 robjects.IntVector(),
robjects.FloatVector()等,看這些名字基本就知道干嘛的了。舉例如下:
print(robjects.IntVector([1,2,3])) print(robjects.FactorVector(['a','a','b','c'])) print(robjects.FloatVector([1.2,2.3])) print(robjects.baseenv) # 基本環境空間 print(robjects.DataFrame({'a':[1,2],'b':[3,4]}))
得到結果如下:
[1] 1 2 3
[1] a a b c
Levels: a b c
[1] 1.2 2.3
<environment: namespace:base>
a.1L a.2L b.3L b.4L
1 1 2 3 4
最后,再來看一個復雜一點的R代碼在Python中的執行情況。
r_script = ''' library(randomForest) # 導入隨機森林包 ## use data set iris data = iris # 使用鳶尾花數據集 table(data$Species) ## create a randomForest model to classfy the iris species # 創建隨機森林模型給鳶尾花分類 iris.rf <- randomForest(Species~., data = data, importance=T, proximity=T) print('--------here is the random model-------') print(iris.rf) print('--------here is the names of model-----') print(names(iris.rf)) confusion = iris.rf$confusion print(confusion) ''' robjects.r(r_script)
得到結果如下:
randomForest 4.6-12
Type rfNews() to see new features/changes/bug fixes.
[1] "--------here is the random model-------"
Call:
randomForest(formula = Species ~ ., data = data, importance = T, proximity = T)
Type of random forest: classification
Number of trees: 500
No. of variables tried at each split: 2
OOB estimate of error rate: 4%
Confusion matrix:
setosa versicolor virginica class.error
setosa 50 0 0 0.00
versicolor 0 47 3 0.06
virginica 0 3 47 0.06
[1] "--------here is the names of model-----"
[1] "call" "type" "predicted" "err.rate"
[5] "confusion" "votes" "oob.times" "classes"
[9] "importance" "importanceSD" "localImportance" "proximity"
[13] "ntree" "mtry" "forest" "y"
[17] "test" "inbag" "terms"
setosa versicolor virginica class.error
setosa 50 0 0 0.00
versicolor 0 47 3 0.06
virginica 0 3 47 0.06
最后,關於python與R在jupyter notebook中交互使用的實例可以參考:http://nbviewer.jupyter.org/gist/xccds/d692e468e21aeca6748a