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:
In the Google Cloud console, go to the User-managed notebooks page.
Select the R instance where you want to install dependencies.
Click Open JupyterLab.
Select File > New > Notebook.
Select the Python 3 kernel for your new notebook file.
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:
In the notebook file's first code cell, enter the following command:
import rpy2.robjects as robjects
ClickRun the selected cells and advance. Python imports rpy2's functions for accessing and manipulating R objects.
To add a code cell, click the notebook file'sInsert a cell below button.
In the new code cell, enter the following:
pi = robjects.r['pi']
ClickRun the selected cells and advance. Python stores an R pi object.
To print the value of pi, in a new code cell, enter
piand click Run the selected cells and advance.
Read rpy2 documentation to learn more about how you can use it to run R and Python code in the same notebook file.