Read a Jupyter/IPython notebook file (.ipynb
) via
jsonlite::fromJSON()
, convert its code cells to R Markdown code
chunks, preserve Markdown cells, and write out the results to an Rmd file.
convert_ipynb(input, output = xfun::with_ext(input, "Rmd"))
input | Path to the input |
---|---|
output | The output file path. |
The output file path (invisibly).
This simple converter may have some rough edges, depending on how many
IPython-specific features are used in a notebook. For example, line magics
are not automatically converted (warnings will be issued if line magics are
detected), but you may consider using or writing R functions to replace them
in R Markdown (e.g., the %load
magic may be replaced by
reticulate::source_python()
). Cell magics will be converted to code
chunks with the (knitr) language engine names being the magic names.
For example, the cell magic %%js
is converted to ```{js}
in R Markdown. This does not always work because not all IPython cell magics
have their counterparts in knitr's language engines, but common cell
magics like %%bash
, %%sh
, %%js
,
%%perl
, %%python
, and %%ruby
should work.
# this is not a real ipynb file, but illustrates what convert_ipynb() does nb_data <- list( cells = list( list(cell_type = 'markdown', source = 'Hi **Markdown**!'), list(cell_type = 'code', source = 'print("Hi R Markdown!")') ), metadata = list( kernelspec = list(language = 'python') ) ) nb_file = tempfile(fileext = '.ipynb') jsonlite::write_json(nb_data, nb_file, auto_unbox = TRUE, pretty = TRUE) xfun::file_string(nb_file) # show file content#> { #> "cells": [ #> { #> "cell_type": "markdown", #> "source": "Hi **Markdown**!" #> }, #> { #> "cell_type": "code", #> "source": "print(\"Hi R Markdown!\")" #> } #> ], #> "metadata": { #> "kernelspec": { #> "language": "python" #> } #> } #> }#> --- #> title: An R Markdown document converted from "/tmp/RtmpRjbJpf/file78be24d51706.ipynb" #> output: html_document #> --- #> #> Hi **Markdown**! #> #> ```{python} #> print("Hi R Markdown!") #> ``` #>