Use R and Python in the same notebook

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

Before you begin

To use R and Python in the same notebook, create a new AI Platform Notebooks instance for R.

Create a notebook for use with R and Python

To use rpy2 to work with both R and Python in the same notebook, create a Python 3 notebook. To create the notebook:

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

    Go to the AI Platform Notebooks page

  2. Select Open JupyterLab for the R instance that you want to open.

  3. Select File -> New -> Notebook. Select the Python 3 kernel for your new notebook. You can also create a Python notebook using the Launcher.

    Add a Python 3 notebook

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

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

Use rpy2 to import R objects

To import R objects with rpy2:

  1. In the notebook's first code cell, enter the following: import rpy2.robjects as robjects.

    Enter the import statement in the first cell

  2. Click the run button. Python imports rpy2's functions for accessing and manipulating R objects.

    The run button

  3. To add a code cell to the notebook, click the notebook's + button.

    The + button

  4. In the new code cell, enter the following: pi = robjects.r['pi'].

  5. Click the run button. Python stores an R pi object.

  6. To print the value of pi, in a new code cell, enter pi[0] and click the run button.

    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.

Was this page helpful? Let us know how we did:

Send feedback about...

AI Platform Notebooks
Need help? Visit our support page.