一个 Jupyter 笔记本中的 R 和 Python [英] R and Python in one Jupyter notebook
问题描述
是否可以在同一个 Jupyter notebook 中运行 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 单元格:
%%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.
这篇关于一个 Jupyter 笔记本中的 R 和 Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!