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:
Go to the AI Platform Notebooks page in the Google Cloud Platform Console.
Select Open JupyterLab for the R instance that you want to open.
Select File -> New -> Notebook. Select the Python 3 kernel for your new notebook. You can also create a Python notebook using the Launcher.
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:
In the notebook's first code cell, enter the following:
import rpy2.robjects as robjects.
Click the run button. Python imports rpy2's functions for accessing and manipulating R objects.
To add a code cell to the notebook, click the notebook's + button.
In the new code cell, enter the following:
pi = robjects.r['pi'].
Click the run button. Python stores an R pi object.
To print the value of pi, in a new code cell, enter
piand click the run button.
Read rpy2 documentation to learn more about how you can use it to run R and Python code in the same notebook.