Is there an equivalent to magic `%run` with R kernel in Jupyter?

834 views Asked by At

This question is somewhat related to Is there a way to do Jupyter cell magic with R.

When you use JupyterLab with a Python kernel, you can split your analysis into several notebooks, like this:

.
├── 01-preprocessing.ipynb
└── 02-analysis.ipynb

and you can start your notebook 02-analysis.ipynb by the magic instruction:

%run 01-preprocessing.ipynb

so that the previous work can be retrieved and continued.

I noticed that this simple solution does not work if those notebooks are R notebooks. Instead, you get an error:

Error in parse(text = x, srcfile = src): <text>:1:1: unexpected input
1: %run 01-preprocessing.ipynb
    ^
Traceback:

As I understand it, the magic commands are not a feature of the Jupyter environment itself: it's a feature of the Python kernel only. But is there any equivalent of that for an R kernel? Or, as an R-user, have you any way to split your analysis between several 'dependent' notebooks like this?

Thanks!

1

There are 1 answers

0
krassowski On BEST ANSWER

Indeed magics are not implemented in IRkernel. As noted by the maintainer here you can use nbconvert.

run_notebook = function(path) {
    if (!file.exists(path)) {
        stop(paste('No such a file:', path))
    }
    eval(
        parse(
            text = system2(
                'jupyter',
                c('nbconvert', path, '--to=script', '--stdout'),
                stdout = TRUE
            )
        )
    )
}
run_notebook('01-preprocessing.ipynb')

This may become easier in the future. There are alternative R kernels that plan to implement magics.