RStudio recently announced the reticulate package, which is designed to help R users inter-operate with Python code. I was immediately excited by this announcement. In a past life, I worked with a team at the National Renewable Energy Lab (NREL) on vehicle simulations. Their models could predict MPG for vehicles based on driving routes. At the time, I had wanted to build a web app that would allow users to predict MPG for different vehicles based on their daily commutes. Unfortunately the model was written in Python, but my web application experience was limited to Shiny. I didn’t want to rewrite the model in R, nor did I have time to learn a Pythonic web framework. Nothing came of the idea…until today*!
Using reticulate, I was able to easily build a Shiny application that used my colleague’s Python code. I also used Python’s Google Maps API client. While R packages exist to work with Google Maps, the Python client is maintained by Google and is simple to access with reticulate.
Checkout the live application and source code.
This post covers a few details and tips for using reticulate, and creating reticulated Shiny apps.
Getting Started
To use reticulate you’ll need to setup Python and any Python dependencies required by your project. We recommend using virtualenv and pip, which are well documented for newcomers.
Once your Python environment is setup, you’ll need to tell the reticulate package to use the environment. reticulate provides the helper functions: use_virtualenv and use_conda. These functions should be called before any other reticulate functions are used. For example, I included the following lines at the top of my app.R file:
library(reticulate)
use_virtualenv('/path/to/myhybrid-project', required = TRUE)
Once your environment is setup, there are two methods for interacting with reticulate code.
Method 1: “Sourcing”
In my case, the Python code my colleagues developed was available in a single Python file. The file consisted of a number of Python functions. To use those functions, I ran source_python('../subdir/with/python-model.py').
Once sourced, I was able to call the Python functions directly as R functions. For example, one of the functions defined in my Python file was sim_drive. The function signature in Python looks like:
def sim_drive( cyc , veh ):
cyc and veh are both Python dictionaries. The function normally returns a complex Python dictionary containing numeric values as well as numpy arrays. In my R code, I can invoke sim_drive as an R function:
results