python与R处理数据都十分方便,不过功能侧重点不是很一样,python作为一种通用型语言用处更加广泛;而R在可视化和统计分析等方面更加方便。有时候在python的代码中插入R的code会更快捷的实现我们想要的功能,rpy2这个包则可以让我们实现这一功能。
- 安装
pip install rpy2
如果安装不上的话,可以试试conda:
conda install -c r rpy2
- 使用
比如如下使用iris数据集,求第一列Sepal.Length的均值:
import rpy2.robjects as robjects
rscript = '''
data(iris)
print(mean(iris$Sepal.Length))
'''
robjects.r(rscript)
这段代码可返回:
![](https://img.haomeiwen.com/i20297934/89460287d8cc7dfe.png)
- 在notebook中直接使用
加载rpy2.ipython:
%load_ext rpy2.ipython
在cell中调用R:
![](https://img.haomeiwen.com/i20297934/83ebe4ea51e17248.png)
画图:
%%R -w 500 -h 300
# 画图
data(iris)
plot(iris$Sepal.Length, iris$Sepal.Width)
![](https://img.haomeiwen.com/i20297934/29ace5690184935c.png)
调用ggplot2画图:
%%R -w 500 -h 300
library(ggplot2)
# data(iris)
p = ggplot(data,aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point(size=4)
print(p
![](https://img.haomeiwen.com/i20297934/be3fe392a2f9476c.png)
这样就可以实现在jupyter notebook中写python的同时也能写R了!
此外,在python中也可以调用shell命令,一个比较简单的方法是导入os模块来实现,如下所示:
import os
os.system("ls") # 列出当前文件夹所有的文件
# 输出test文件的内容
os.system(os.system("awk '{print $0}' test.txt"))
![](https://img.haomeiwen.com/i20297934/0ec4d20a2144b62f.png)
网友评论