Jupyter Notebooks - rlsweeney/Sweeney_RA_Manual GitHub Wiki

Jupyter notebooks are web-based computational environments. One benefit of using them is that it's easy to produce readable documents that include code and code output. Another benefit is that this same environment can be used to call many different computational tools. Notes on installing these "kernels" below.

Note that Jupyter relies on Python, so you need to have that setup first. If you haven't done this, Quantitative Economics has detailed instructions.

Matlab

You can call MATLAB from within Jupyter notebooks. Can then embed markdown / latex along side collapsible MATLAB code in a single document.

Setup

I primarily followed these steps when setting this up. My setup is Windows though, so I'll include anything different I did below.

Step 1: Install MATLAB Engine for Python
From the MATLAB website

cd "matlabroot\extern\engines\python"
python setup.py install

Step 2: Install the python matlab kernel
From command prompt:

pip install matlab_kernel
python -m matlab_kernel install

To check install, type: jupyter kernelspec list

How to use it

  • To launch a Jupyter notebook, type jupyter notebook (from whatever directory you want to work in).
  • This will open up a browser. If you click "new" on the right, you should see MATLAB as an option.
  • Within this new notebook, and code chunks you submit will be interpreted by MATLAB.

R

Installing an R kernel is easy (after you've setup Anaconda)

install.packages('IRkernel')
library(IRkernel)
IRkernel::installspec()

You should be able to use the R kernel now. When running in browser via jupyter notebook, this worked immediately for me.

In VS Code this didn't work right a way, but I think updating via this slack thread worked. After that, start a new .ipynb in VSCode and select select kernel (top right) > Jupyter kernel... > R.. (note make sure the R path matches the main install.

Tips and Tricks

List installed kernels

jupyter kernelspec list

Suppress some cells from processed Jupyter output.

I use this to have a single document for problem sets that can produce both question and answer pdfs.

Solution from this stack post

  • in your notebook, add a tag to cells you want to remove
    • for example, I tag answer cells with the tag solutions
  • compile notebook with nbconvert, invoking the TagRemovePreprocessor.remove_cell_tags option.
    • Note: make sure you pip install nbconvert --upgrade first! ( took me forever to realize this was causing me problems)
  • Here is an example, which processes a problem set and saves two separate files:
jupyter nbconvert --execute pset.ipynb --output pset-questions --TagRemovePreprocessor.remove_cell_tags="{'solutions'}"

jupyter nbconvert --execute pset.ipynb --output pset-solutions