Search code examples
rjupyter-notebookjupyter-irkernel

Using ipython magics in R jupyter notebook?


I installed jupyter with conda install jupyter and am running a notebook with the r kernal installed from conda create -n my-r-env -c r r-essentials

I am running a notebook and want to run a bash command from a shell.

!echo "hi"
Error in parse(text = x, srcfile = src): <text>:1:7: unexpected string constant
1: !echo "hi"

For comparison, in an notebook with a python kernel:

!echo "hi"
hi

Is there a way to set up R notebooks to have the same functionality as the ipython notebook with regards to bash commands (and maybe other magics)?


Solution

  • For just bash commands, it's possible to get system commands to work. For example, in the IRkernel:

    system("echo 'hi'", intern=TRUE)
    

    Output:

    'hi'
    

    Or to see the first 5 lines of a file:

    system("head -5 data/train.csv", intern=TRUE)
    

    As IPython magics are available in the IPython kernel (but not in the IRkernel), I did a quick check if it was possible to access these using the rPython and PythonInR libraries. However, the issue is that get_ipython() isn't visible to the Python code, so none of the following worked:

    library("rPython")
    rPython::python.exec("from IPython import get_ipython; get_ipython().run_cell_magic('writefile', 'test.txt', 'This is a test')")
    
    library("PythonInR")
    PythonInR::pyExec("from IPython import get_ipython; get_ipython().run_cell_magic('head -5 data/test.csv')")