Interweaving R and Python with Reticulate

 

Python is my favorite language for data manipulation, but every once in a while, I find an R library that I absolutely need to try out. I wish I could have the best of both worlds. Unfortunately, I had not found a good solution until recently, when I tried out RStudio and the Reticulate R package, and the combination is awesome!

With Reticulate and the new version of RStudio (RStudio 1.2), you can create Python code chunks that have a persistent environment across them within a single Rmarkdown document. This turns RStudio into a powerful alternative to the popular Jupyter notebook for Python development.

A simple demonstration:

R code:

# Loading the Reticulate library in RStudio
library(reticulate)

Now some Python:

# Creating a couple of simple arrays to plot
import numpy as np

x = np.array([1, 2, 3, 4, 5, 5])
y = np.exp2(x)


# Displaying a python plot
import matplotlib.pyplot as plt

plt.plot(x, y)
plt.show()

image

Furthermore, you can access these same Python objects from inside an R code cell, so now, you can finally have the best of both worlds!

# Plotting the same arrays in R! So simple!
plot(py$x, py$y)

image

I normally do most of my coding in Vim, or Jupyter notebooks, but after discovering this package, I think I will be using RStudio a lot more often for Python + R programming.

Previously, my attempts at combining Python and R code involved using the Python rpy2 library to call R code within Python, but this approach always felt cumbersome at best. By comparison, Reticulate makes the transition feel smooth and natural, effectively marrying the powerful libraries of R and Python.