在R语言方面就缺乏这类工具,不过ipython有一种“魔法”,可以在ipython中运行其它语言。在数据分析时,可以将python和R代码混编,充分利用两种语言的优势。以可视化为例,R的ggplot2图形语法可谓是独步江湖,python中虽然已经有不少优秀的绘图库。但总不及ggplot2用得习惯。下面的小例子就是示范在ipython notebook中画ggplot2。
首先是用numpy库建立两个向量,再用%load_ext建立python和R的连接机制。之后在ipython notebook的一个cell里面就可以使用%R后面接R代码行,或者使用%%R使用代码块。如果要在R代码块中读入python的对象,需要使用-i参数。
其它例子可以参见这个,python中也有人复制了ggplot语法,可参见这里。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
x = np.random.randn(100) | |
y = 2*x + np.random.randn(100) | |
%load_ext rpy2.ipython | |
%%R -i x,y -w 500 -h 300 | |
df <- data.frame(x,y) | |
m <- lm(y~x) | |
inter <- m$coef[1] | |
slop <- m$coef[2] | |
library(ggplot2) | |
p <- ggplot(df, aes(x,y)) | |
p <- p + | |
geom_point() + | |
geom_abline(intercept = inter, slope = slop) | |
print(p) |