<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/reticulated-shiny/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://rviews.rstudio.com/2018/04/17/reticulated-shiny/"> R Views</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>RStudio recently announced the <a rel="nofollow" href="https://blog.rstudio.com/2018/03/26/reticulate-r-interface-to-python/" target="_blank"><code>reticulate</code> package</a>, 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*!</p>
<p>Using <code>reticulate</code>, 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 <code>reticulate</code>.</p>
<p>Checkout the <a rel="nofollow" href="http://colorado.rstudio.com/rsc/content/1025/" target="_blank">live application</a> and <a rel="nofollow" href="https://github.com/slopp/myhybrid" target="_blank">source code</a>.</p>
<p><img alt="Screen shot of a reticulated Shiny app" src="https://i2.wp.com/rviews.rstudio.com/post/2018-04-18-reticulated-shiny/app-screenshot.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>This post covers a few details and tips for using <code>reticulate</code>, and creating reticulated Shiny apps.</p>
<h2>Getting Started</h2>
<p>To use <code>reticulate</code> you’ll need to setup Python and any Python dependencies required by your project. We recommend using <code>virtualenv</code> and <code>pip</code>, which are <a rel="nofollow" href="https://www.dabapps.com/blog/introduction-to-pip-and-virtualenv-python/" target="_blank">well documented</a> for newcomers.</p>
<p>Once your Python environment is setup, you’ll need to tell the <code>reticulate</code> package to use the environment. <code>reticulate</code> provides the helper functions: <code>use_virtualenv</code> and <code>use_conda</code>. These functions should be called before any other <code>reticulate</code> functions are used. For example, I included the following lines at the top of my <code>app.R</code> file:</p>
<pre><code>library(reticulate)
use_virtualenv('/path/to/myhybrid-project', required = TRUE)
</code></pre>
<p>Once your environment is setup, there are two methods for interacting with <code>reticulate</code> code.</p>
<h2>Method 1: “Sourcing”</h2>
<p>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 <code>source_python('../subdir/with/python-model.py')</code>.</p>
<p>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 <code>sim_drive</code>. The function signature in Python looks like:</p>
<pre><code>def sim_drive( cyc , veh ):
</code></pre>
<p><code>cyc</code> and <code>veh</code> 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 <code>sim_drive</code> as an R function:</p>
<pre><code>results &lt;- sim_drice(cyc, veh)
</code></pre>
<p>In my case, <code>cyc</code> and <code>veh</code> are R data frames and <code>results</code> will be an R list. <code>reticulate</code> handles all of the conversions between R and Python automatically. (This worked the first time I tried it; I was literally giddy!).</p>
<p>If your Python file doesn’t contain functions, but also creates objects, use <code>py_run_file</code> instead of <code>source_python</code> and then access the Python objects using <code>py$object</code>.</p>
<h2>Method 2: “Importing”</h2>
<p>The second method for writing reticulated code is to import Python objects and write R code that uses those references. This method is helpful if you don’t have existing Python files, but instead want to access Python classes or methods.</p>
<p>For my app, I wanted to make use of the Google Maps Python client maintained by Google. The Google help documentation provides sample Python code to query the Directions API:</p>
<pre><code>import googlemaps
import os

from datetime import datetime

gmaps = googlemaps.Client(key=os.environ['DIRECTIONS_API_KEY'])
  
def get_route(start, end):
  route = gmaps.directions(start,
                                end,
                                mode = &quot;driving&quot;, 
                                departure_time  = datetime.now())
  return(route)
</code></pre>
<p>Using reticulate, I was able to write similar R code that utilized the same Python objects:</p>
<pre><code>googlemaps &lt;- import('googlemaps')

gmaps &lt;- googlemaps$Client(key = Sys.getenv('DIRECTIONS_API_KEY'))
  
get_route &lt;- function(start, end) {
  
  route &lt;- gmaps$directions(
            start,
            end,
            mode = &quot;driving&quot;, 
            departure_time  = Sys.time())
  return(route)
  
}
</code></pre>
<p>I was able to swap some of the Python components with R code; for example I used <code>Sys.time</code> and <code>Sys.getenv</code> in place of <code>datetime</code> and <code>os</code>. <code>reticulate</code>’s flexibility lets you interweave R and Python code.</p>
<p>The resulting <code>routes</code> object is a complex nested list. I opted to use <code>purrr</code> to process this list, but if you were familiar with Python tools, you could continue to write reticulated code. <code>reticulate</code> enables you to pick the pieces from each language that you like best. The remainder of the application logic is written in R, including the use of <code>SMA</code> for smoothing and a fair subset of the <code>tidyverse</code> for tidying and plotting data. I’d be remiss if I didn’t include a brief shout-out to the <code>shinymaterial</code> package for providing an appealing and easy-to-use shiny theme.</p>
<h2>Deployment</h2>
<p>Like any Shiny application, a reticulated Shiny app has to be deployed in order for others to leverage the app. Reticulated Shiny apps can be deployed like regular Shiny apps, but take care to ensure that the deployment server has the same Python environment.</p>
<h2>Parting Thoughts</h2>
<p><code>reticulate</code> helped me accomplish a task that I had been day dreaming about for years. You don’t need to be a Python expert, but you do get many of the benefits.<br>
The <a rel="nofollow" href="https://rstudio.github.io/reticulate/" target="_blank"><code>reticulate</code> website</a> explains that the name of the package comes from the interweaving color pattern found on reticulated pythons. I found interweaving Python and R to create reticulated R code powerful and enjoyable. I can’t wait to see more examples of this new breed of code!</p>
<h2>*Disclaimer</h2>
<p>Access to NREL’s FASTSim model used in this demo is available <a rel="nofollow" href="https://www.nrel.gov/transportation/fastsim.html" target="_blank">here</a>. The Shiny application was developed independently by RStudio as a demo using the freely available FASTSim model. The application was not written in conjunction with the National Renewable Energy Lab (NREL), nor is the application endorsed by NREL. The results presented in the application are not to be used for accurate vehicle comparisons. RStudio is NOT RESPONSIBLE for the accuracy or reliability of any results presented in the application.</p>
<p> </p>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://rviews.rstudio.com/2018/04/17/reticulated-shiny/"> R Views</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img width="1" alt="" src="http://feeds.feedburner.com/~r/RBloggers/~4/OvOwbAL5sk8" height="1"></a></div>