Skip to content

Convert between R markdown and Jupyter notebook

License

Notifications You must be signed in to change notification settings

cloudy-sfu/Jupyter-R-bridge

Repository files navigation

Jupyter R Bridge

Convert between R markdown and Jupyter notebook

Compare

This table lists the difference between exporting Jupyter notebook and knitting R markdown.

Description Jupyter notebook R markdown Knit
Support chunk options1 specified in the code chunk header of Markdown code blocks.
Preview graphs created by grid library. 2

Make Jupyter Lab support R

Windows 10

  1. Create a Python virtual environment. Denote its absolute path is $venv.

  2. Run pip install jupyterlab in Python environment to install Jupyter Lab.3 It will create a file $venv\Scripts\jupyter-lab.exe.

  3. Run the following script in R terminal, replacing all backslash \ with /.4

    # Python environment. Use slash '/' only.
    setwd('$venv/Scripts')
    install.packages("IRkernel")
    IRkernel::installspec()
  4. Create a directory to save your projects. Denote the path is $JupyterLab.

  5. Run the following script to start Jupyter lab.

    netstat -ano | findstr :8888
    cd $JupyterLab
    $venv\Scripts\jupyter-lab.exe --port 8888

Ubuntu 20.04

  1. Install Jupyter Lab according to the Python environment.

    • If using "miniconda" or alternatives, run the following command, where $env_name is a customized string.

      conda create -n $env_name python=3.11
      pip install jupyterlab
      cd ~/.conda/envs/$env_name/bin/
      R
    • If using virtual environments, run the following command.

      venv=$(which python)
      cd $venv/bin/
      R
      
  2. In R command line, run the following command to install R kernel for Jupyter lab.

    install.packages("IRkernel")
    IRkernel::installspec()
    quit()
  3. If you access Ubuntu machine by SSH, run the following command to start Jupyter lab.

    cd ~
    jupyter-lab --port 6007 --no-browser --ip 0.0.0.0

    You can customize the port 6007, but should not modify IP address 0.0.0.0.

    If you use Ubuntu machine and access Jupyter lab locally (without SSH), run the following command to start Jupyter lab.

    cd ~
    jupyter-lab --port 6007
  4. [Optional] Start a SSH tunnel, therefore notebooks can be visited remotely. In Windows client, start MobaXTerm and config as follows.

    Local port forwarding

    Remote server: 0.0.0.0

    Remote port: 6007

    Forwarded port: 6007

Export R Studio shortcuts

Export customized key bindings setting by copying the files in %APPDATA%/RStudio/keybindings.

Acknowledgement

We use rmd2jupyter to convert *.Rmd to *.ipynb. The script is modified.

Footnotes

  1. For example, {r warning=FALSE} to suppress warnings; {r fig.width=5, fig.height=5} to adjust figure size.

  2. In R Studio, write grid.newpage() at the beginning of each chunk to fix it.

  3. https://jupyter.org/install

  4. https://izoda.github.io/site/anaconda/r-jupyter-notebook/