3.9 Jupyter Notebooks

Jupyter (formerly IPython Notebook) is an open-source project that lets you easily combine Markdown text and executable Python source code on one canvas called a notebook. It provides an interactive environment where you can write and execute code, visualize data, and document your analysis all in one place.

It sounds like R Markdown.

  • One distinction is that R Markdown runs code in R console, while Jupyter notebook runs code in its own kernel.

  • Jupyter can provide individual environments for each notebook, making it easier to manage dependencies and avoid conflicts between different projects. → But probably, it’s easier just to use the system R kernel as you don’t need to install packages in each environment.

    • You can use conda install to manage packages in each independent environment.
  • Magic commands

    This can be used to run code in different languages within the same notebook. For example, you can use the %%R magic command to run R code in a Python notebook, or the %%python magic command to run Python code in an R notebook.

    There are many other magic commands available, such as %%bash to run shell commands, %%time to time the execution of a cell, and %%cd to change the current working directory.

  • Online services

    You may have web-based access to Jupyter notebooks via services such as Google Colab, JupyterHub and Open OnDemand.

  • You can convert Jupyter notebooks to Quarto qmd format:

    quarto convert demo-python.ipynb

    This is nice in part because qmd (like Rmd) is more easily handled by version control and with shell commands than the JSON format of .ipynb files.

Tutorial:

  1. Install IRkernel

    install.packages("IRkernel")
    IRkernel::installspec() 
    • Note this needs to be run in the R terminal or Radian (running in RStudio does not work).
    • IRkernel::installspec() makes the R kernel available to Jupyter. It lets Jupyter to use the default system R kernel instead of the R provided by Anaconda.
  2. Reload window. Open command palette and type “Jupyter: Create New Blank Notebook” to create a new Jupyter notebook.

  3. Click on the button right below ellipsis in upper right corner to choose kernel

    • Select Jupyter Kernels > R to use the R kernel.

      It should look something like this: