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 user-managed 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. In the Google Cloud console, go to the User-managed notebooks page.

    Go to User-managed notebooks

  2. Select the R instance where you want to install dependencies.

  3. Click Open JupyterLab.

  4. Select File > New > Notebook.

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

  6. 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.