Body
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.
2. Set conda-forge channel to highest priority in channel list.
3. Install rpy2 package in the active conda environment, enter "conda install rpy2".
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()".