Use R and Python in the same notebook file

This page describes how to use Python's rpy2 package to run R and Python code in the same notebook file.

Before you begin

Before you begin, create an R framework Notebooks instance.

Create a notebook file for use with R and Python

To use R and Python in the same notebook file, complete these steps:

  1. Go to the Notebooks page in the Google Cloud Console.

    Go to the Notebooks page

  2. Next to the R instance that you want to open, click Open JupyterLab.

  3. Select File > New > Notebook.

    Add a Python 3 notebook file

  4. Select the Python 3 kernel for your new notebook file.

  5. Select File > Rename notebook and change the name of the untitled notebook file to something meaningful, such as "rpy2.ipynb."

    The notebook file is ready for you to import rpy2 and use R and Python in the same workbook.

Use rpy2 to import R objects

As an example of how to use R and Python in the same notebook file, complete the following steps to import R objects with rpy2:

  1. In the notebook file's first code cell, enter the following command:

    import rpy2.robjects as robjects
    
  2. Click Run the selected cells and advance. Python imports rpy2's functions for accessing and manipulating R objects.

    The Run the selected cells and advance button

  3. To add a code cell, click the notebook file's Insert a cell below button.

    The Insert a cell below button

  4. In the new code cell, enter the following:

    pi = robjects.r['pi']
    
  5. Click Run the selected cells and advance. Python stores an R pi object.

  6. To print the value of pi, in a new code cell, enter pi[0] and click Run the selected cells and advance.

    Print the value of pi

What's next

Read rpy2 documentation to learn more about how you can use it to run R and Python code in the same notebook file.