r - Jupyter 可以从 Python 笔记本中运行单独的 R 笔记本吗?

标签 r ipython jupyter-notebook ipython-notebook jupyter-irkernel

我有一个 Jupyter 笔记本(python3),它是一个批处理作业——它使用 %run 运行三个独立的 python3 笔记本.我想从我的批次中调用第四个 Jupyter R-kernel 笔记本。

有没有办法在 Jupyter/iPython 中从 Python 笔记本执行外部 R 笔记本?

当前设置:
run_all.ipynb :(python3内核)

%run '1_py3.ipynb'
%run '2_py3.ipynb'
%run '3_py3.ipynb'
%run '4_R.ipynb'

三个 python3 notebook 运行正常。 R 笔记本在 Jupyter 中单独打开时可以正常运行——但是在使用 %run 调用时会失败来自 run_all.ipynb .它被解释为python,并且单元格在第一行给出了python错误:

cacheDir <- "caches"

TypeError: bad operand type for unary -: 'str'



我对从 python 笔记本运行单独的 R 笔记本的任何解决方案感兴趣——Jupyter magic、shell、python 库等等。我也会对解决方法感兴趣 - 例如一种方法(如 shell 脚本)可以运行所有四个笔记本(python3 和 R),即使这不能从 python3 笔记本内部完成。

(注意:我已经了解如何在单元格中嵌入 %%R。这不是我想要做的。我想调用一个完整的独立 R 笔记本。)

最佳答案

我认为您不能使用 %run在当前内核中执行文件时,以这种方式执行magic命令。

Nbconvert 有一个执行 API,允许您执行笔记本。因此,您可以创建一个 shell 脚本来执行您的所有笔记本,如下所示:

#!/bin/bash
jupyter nbconvert --to notebook --execute 1_py3.ipynb
jupyter nbconvert --to notebook --execute 2_py3.ipynb
jupyter nbconvert --to notebook --execute 3_py3.ipynb
jupyter nbconvert --to notebook --execute 4_R.ipynb

由于您的笔记本不需要共享状态,因此应该没问题。或者,如果您真的想在笔记本中执行此操作,则可以使用 execute Python API 从笔记本中调用 nbconvert。
import nbformat
from nbconvert.preprocessors import ExecutePreprocessor

with open("1_py3.ipynb") as f1, open("2_py3.ipynb") as f2, open("3_py3.ipynb") as f3, open("4_R.ipynb") as f4:
    nb1 = nbformat.read(f1, as_version=4)
    nb2 = nbformat.read(f2, as_version=4)
    nb3 = nbformat.read(f3, as_version=4)
    nb4 = nbformat.read(f4, as_version=4)

ep_python = ExecutePreprocessor(timeout=600, kernel_name='python3')
#Use jupyter kernelspec list to find out what the kernel is called on your system
ep_R = ExecutePreprocessor(timeout=600, kernel_name='ir')

# path specifies which folder to execute the notebooks in, so set it to the one that you need so your file path references are correct
ep_python.preprocess(nb1, {'metadata': {'path': 'notebooks/'}})
ep_python.preprocess(nb2, {'metadata': {'path': 'notebooks/'}})
ep_python.preprocess(nb3, {'metadata': {'path': 'notebooks/'}})
ep_R.preprocess(nb4, {'metadata': {'path': 'notebooks/'}})

with open("1_py3.ipynb", "wt") as f1, open("2_py3.ipynb", "wt") as f2, open("3_py3.ipynb", "wt") as f3, open("4_R.ipynb", "wt") as f4:
    nbformat.write(nb1, f1)
    nbformat.write(nb2, f2)
    nbformat.write(nb3, f3)
    nbformat.write(nb4, f4)

请注意,这几乎只是从 nbconvert 执行 API 文档中复制的示例:link

关于r - Jupyter 可以从 Python 笔记本中运行单独的 R 笔记本吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47047376/

相关文章:

r - 如何从R中的不同函数依次将数据写入csv文件?

r - R中的展开函数?

r - 如何使用单独的表来过滤数据

ipython - 如何使用 .ipynb 文件在 IPython 笔记本中保存 .py 文件

matlab - 如何在 Jupyter Notebook 中编写 MATLAB 函数?

jupyter-notebook - 将 nbconvert 升级到 6.x+ 时如何解决 TemplateNotFound 错误?

python - 如何从 Jupyter 在 HDInsight Spark 集群上提交 python wordcount

r - 修复 R 中返回栅格单元之间距离数据帧的函数瓶颈

python - IPython Notebook 小部件的 Bokeh : extra figures apppearing

docker - Python KafkaConsumer无法连接