R和Python在一个Jupyter笔记本中 [英] R and Python in one Jupyter notebook
问题描述
是否可以在同一个Jupyter笔记本中运行R和Python代码。什么是可用的替代品?
Is it possible to run R and Python code in the same Jupyter notebook. What are all the alternatives available?
- 在Jupyter中安装r-essentials并创建R笔记本。
- 安装rpy2并使用rmagic函数。
- 使用烧杯笔记本。
以上哪项3个选项可靠运行Python和R代码片段(共享变量和可视化)或者是否有更好的选择?
Which of above 3 options is reliable to run Python and R code snippets (sharing variables and visualizations) or is there a better option already?
推荐答案
对的,这是可能的!使用rpy2。
Yes, it is possible! Use rpy2.
您可以安装rpy2: pip install rpy2
You can install rpy2 with: pip install rpy2
然后在你的一个单元格中运行%load_ext rpy2.ipython
。 (您只需运行一次。)
Then run %load_ext rpy2.ipython
in one of your cells. (You only have to run this once.)
现在您可以执行以下操作:
Now you can do the following:
Python单元格:
Python cell:
# enables the %%R magic, not necessary if you've already done this
%load_ext rpy2.ipython
import pandas as pd
df = pd.DataFrame({
'cups_of_coffee': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
'productivity': [2, 5, 6, 8, 9, 8, 0, 1, 0, -1]
})
R cell:
R cell:
%%R -i df -w 5 -h 5 --units in -r 200
# import df from global environment
# make default figure size 5 by 5 inches with 200 dpi resolution
install.packages("ggplot2", repos='http://cran.us.r-project.org', quiet=TRUE)
library(ggplot2)
ggplot(df, aes(x=cups_of_coffee, y=productivity)) + geom_line()
而且你将从python Pandas DataFrame中获得你的漂亮图形数据。
And you'll get your pretty figure plotting data from a python Pandas DataFrame.
这篇关于R和Python在一个Jupyter笔记本中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!