How-To: Using Anaconda: Use rpy2 Package to Manage Python-R Integration

Question

How do I install and use rpy2 to run R code inside Python?

 

Answer

1. Create and activate a new conda environment for use with R & Rstudio.

Note:  To create a conda environment for using Rstudio, see "How-To: Rstudio: Create Conda Environment for Using Rstudio"

 

2. Set conda-forge channel to highest priority in channel list.

 

3. Install rpy2 package in the active conda environment, enter "conda install rpy2". 

 

 

Note:  To install RTools in a conda environment, see " How To: Manually Install Rtools as a User "

4. For Windows with RTools installed per linked instructions above only: in the current Anaconda Prompt active conda environment, configure Windows Environment Variables by entering the below set commands.

set R_HOME=%CONDA_PREFIX%\Lib\R
set PATH=%CONDA_PREFIX%\Lib\R\bin\x64;%UserProfile%\rtools45\usr\bin;%PATH%

 

 

5. To verify that the bridge between Python and R is functioning seamlessly, test it using a quick Python interactive session in the current active conda environment.

a. Launch Python, enter "python".

b. Run the following script to execute native R code inside Python:

 

import rpy2.robjects as robjects
# Evaluate a basic R string
robjects.r('print("Hello from the R ecosystem!")')
# Create an R vector from a Python list and calculate the mean
r_vector = robjects.IntVector([10, 20, 30, 40, 50])
r_mean = robjects.r['mean'](r_vector)
print(f"Calculated Mean via R: {r_mean[0]}")

 

c. If it successfully returns 30.0, your cross-language pipeline is officially open for business.

d. Exit python, enter "quit()".

Print Article

Related Articles (4)

Quick start guide to using R, Rstudio and Python together on University-managed computers including installation without administrator credentials, utilization of unique conda environments for each project, adding additional channels for packages, adding R and Python packages to the environment, launching Rstudio, utilizing the reticulate R package and backing up configurations for portability and reproducibility.
Index of Advanced Topics for Conda, Python, and R
Index of Articles for Managed Virtual Conda Environments
Index of Miniconda How-To Articles for Virtual Conda Environments