<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/reticulate-r-interface-to-python/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://blog.rstudio.com/2018/03/26/reticulate-r-interface-to-python/"> RStudio Blog</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p>We are pleased to announce the <strong>reticulate</strong> package, a comprehensive set of tools for interoperability between Python and R. The package includes facilities for:</p>
<p><img alt="reticulated python" align="right" src="https://i2.wp.com/rstudio.github.io/reticulate/images/reticulated_python.png?w=200&ssl=1" data-recalc-dims="1"></p>
<ul>
<li>
<p>Calling Python from R in a variety of ways including R Markdown, sourcing Python scripts, importing Python modules, and using Python interactively within an R session.</p>
</li>
<li>
<p>Translation between R and Python objects (for example, between R and Pandas data frames, or between R matrices and NumPy arrays).</p>
</li>
<li>
<p>Flexible binding to different versions of Python including virtual environments and Conda environments.</p>
</li>
</ul>
<p>Reticulate embeds a Python session within your R session, enabling seamless, high-performance interoperability. If you are an R developer that uses Python for some of your work or a member of data science team that uses both languages, reticulate can dramatically streamline your workflow!</p>
<p>You can install the <strong>reticulate</strong> pacakge from CRAN as follows:</p>
<pre><code>install.packages(&quot;reticulate&quot;)
</code></pre>
<p>Read on to learn more about the features of reticulate, or see the <a rel="nofollow" href="https://rstudio.github.io/reticulate" target="_blank">reticulate website</a> for detailed documentation on using the package.</p>
<h2>Python in R Markdown</h2>
<p>The <strong>reticulate</strong> package includes a Python engine for <a rel="nofollow" href="http://rmarkdown.rstudio.com/" target="_blank">R Markdown</a> with the following features:</p>
<ul>
<li>
<p>Run Python chunks in a single Python session embedded within your R session (shared variables/state between Python chunks)</p>
</li>
<li>
<p>Printing of Python output, including graphical output from <a rel="nofollow" href="https://matplotlib.org/" target="_blank">matplotlib</a>.</p>
</li>
<li>
<p>Access to objects created within Python chunks from R using the <code>py</code> object (e.g. <code>py$x</code> would access an <code>x</code> variable created within Python from R).</p>
</li>
<li>
<p>Access to objects created within R chunks from Python using the <code>r</code> object (e.g. <code>r.x</code> would access to <code>x</code> variable created within R from Python)</p>
</li>
</ul>
<div></div>
<p>Built in conversion for many Python object types is provided, including <a rel="nofollow" href="http://www.numpy.org/" target="_blank">NumPy</a> arrays and <a rel="nofollow" href="https://pandas.pydata.org/" target="_blank">Pandas</a> data frames. From example, you can use Pandas to read and manipulate data then easily plot the Pandas data frame using <a rel="nofollow" href="http://ggplot2.org/" target="_blank">ggplot2</a>:</p>
<p><img src="https://i1.wp.com/rstudio.github.io/reticulate/images/rmarkdown_engine_zoomed.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>Note that the reticulate Python engine is enabled by default within R Markdown whenever reticulate is installed.</p>
<p>See the <a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/r_markdown.html" target="_blank">R Markdown Python Engine</a> documentation for additional details.</p>
<h2>Importing Python modules</h2>
<p>You can use the <code>import()</code> function to import any Python module and call it from R. For example, this code imports the Python <code>os</code> module and calls the <code>listdir()</code> function:</p>
<pre><code>library(reticulate)
os &lt;- import(&quot;os&quot;)
os$listdir(&quot;.&quot;)
</code></pre>
<pre><code> [1] &quot;.git&quot;             &quot;.gitignore&quot;       &quot;.Rbuildignore&quot;    &quot;.RData&quot;          
 [5] &quot;.Rhistory&quot;        &quot;.Rproj.user&quot;      &quot;.travis.yml&quot;      &quot;appveyor.yml&quot;    
 [9] &quot;DESCRIPTION&quot;      &quot;docs&quot;             &quot;external&quot;         &quot;index.html&quot;      
[13] &quot;index.Rmd&quot;        &quot;inst&quot;             &quot;issues&quot;           &quot;LICENSE&quot;         
[17] &quot;man&quot;              &quot;NAMESPACE&quot;        &quot;NEWS.md&quot;          &quot;pkgdown&quot;         
[21] &quot;R&quot;                &quot;README.md&quot;        &quot;reticulate.Rproj&quot; &quot;src&quot;             
[25] &quot;tests&quot;            &quot;vignettes&quot;      
</code></pre>
<p>Functions and other data within Python modules and classes can be accessed via the <code>$</code> operator (analogous to the way you would interact with an R list, environment, or reference class).</p>
<p>Imported Python modules support code completion and inline help:</p>
<p><img src="https://i0.wp.com/rstudio.github.io/reticulate/images/reticulate_completion.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>See <a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/calling_python.html" target="_blank">Calling Python from R</a> for additional details on interacting with Python objects from within R.</p>
<h2>Sourcing Python scripts</h2>
<p>You can source any Python script just as you would source an R script using the <code>source_python()</code> function. For example, if you had the following Python script <em>flights.py</em>:</p>
<pre><code>import pandas

def read_flights(file):
  flights = pandas.read_csv(&quot;flights.csv&quot;)
  flights = flights[flights['dest'] == &quot;ORD&quot;]
  flights = flights[['carrier', 'dep_delay', 'arr_delay']]
  flights = flights.dropna()
  return flights
</code></pre>
<p>Then you can source the script and call the <code>read_flights()</code> function as follows:</p>
<pre><code>source_python(&quot;flights.py&quot;)
flights &lt;- read_flights(&quot;flights.csv&quot;)

library(ggplot2)
ggplot(flights, aes(carrier, arr_delay)) + geom_point() + geom_jitter()
</code></pre>
<p>See the <a rel="nofollow" href="https://rstudio.github.io/reticulate/reference/source_python.html" target="_blank"><code>source_python()</code></a> documentation for additional details on sourcing Python code.</p>
<h2>Python REPL</h2>
<p>If you want to work with Python interactively you can call the <code>repl_python()</code> function, which provides a Python REPL embedded within your R session. Objects created within the Python REPL can be accessed from R using the <code>py</code> object exported from reticulate. For example:</p>
<p><img src="https://i0.wp.com/rstudio.github.io/reticulate/images/python_repl.png?w=456&ssl=1" data-recalc-dims="1"></p>
<p>Enter <code>exit</code> within the Python REPL to return to the R prompt.</p>
<p>Note that Python code can also access objects from within the R session using the <code>r</code> object (e.g. <code>r.flights</code>). See the <a rel="nofollow" href="https://rstudio.github.io/reticulate/reference/repl_python.html" target="_blank"><code>repl_python()</code></a> documentation for additional details on using the embedded Python REPL.</p>
<h2>Type conversions</h2>
<p>When calling into Python, R data types are automatically converted to their equivalent Python types. When values are returned from Python to R they are converted back to R types. Types are converted as follows:</p>
<table>
<thead>
<tr>
<th>R</th>
<th>Python</th>
<th>Examples</th>
</tr>
</thead>
<tbody>
<tr>
<td>Single-element vector</td>
<td>Scalar</td>
<td><code>1</code>, <code>1L</code>, <code>TRUE</code>, <code>&quot;foo&quot;</code></td>
</tr>
<tr>
<td>Multi-element vector</td>
<td>List</td>
<td><code>c(1.0, 2.0, 3.0)</code>, <code>c(1L, 2L, 3L)</code></td>
</tr>
<tr>
<td>List of multiple types</td>
<td>Tuple</td>
<td><code>list(1L, TRUE, &quot;foo&quot;)</code></td>
</tr>
<tr>
<td>Named list</td>
<td>Dict</td>
<td><code>list(a = 1L, b = 2.0)</code>, <code>dict(x = x_data)</code></td>
</tr>
<tr>
<td>Matrix/Array</td>
<td>NumPy ndarray</td>
<td><code>matrix(c(1,2,3,4), nrow = 2, ncol = 2)</code></td>
</tr>
<tr>
<td>Data Frame</td>
<td>Pandas DataFrame</td>
<td><code>data.frame(x = c(1,2,3), y = c(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;))</code></td>
</tr>
<tr>
<td>Function</td>
<td>Python function</td>
<td><code>function(x) x + 1</code></td>
</tr>
<tr>
<td>NULL, TRUE, FALSE</td>
<td>None, True, False</td>
<td><code>NULL</code>, <code>TRUE</code>, <code>FALSE</code></td>
</tr>
</tbody>
</table>
<p>If a Python object of a custom class is returned then an R reference to that object is returned. You can call methods and access properties of the object just as if it was an instance of an R reference class.</p>
<h2>Learning more</h2>
<p>The <a rel="nofollow" href="https://rstudio.github.io/reticulate/" target="_blank">reticulate website</a> includes comprehensive documentation on using the package, including the following articles that cover various aspects of using reticulate:</p>
<ul>
<li>
<p><a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/calling_python.html" target="_blank">Calling Python from R</a> — Describes the various ways to access Python objects from R as well as functions available for more advanced interactions and conversion behavior.</p>
</li>
<li>
<p><a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/r_markdown.html" target="_blank">R Markdown Python Engine</a> — Provides details on using Python chunks within R Markdown documents, including how call Python code from R chunks and vice-versa.</p>
</li>
<li>
<p><a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/versions.html" target="_blank">Python Version Configuration</a> — Describes facilities for determining which version of Python is used by reticulate within an R session.</p>
</li>
<li>
<p><a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/python_packages.html" target="_blank">Installing Python Packages</a> — Documentation on installing Python packages from PyPI or Conda, and managing package installations using virtualenvs and Conda environments.</p>
</li>
<li>
<p><a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/package.html" target="_blank">Using reticulate in an R Package</a> — Guidelines and best practices for using reticulate in an R package.</p>
</li>
<li>
<p><a rel="nofollow" href="https://rstudio.github.io/reticulate/articles/arrays.html" target="_blank">Arrays in R and Python</a> — Advanced discussion of the differences between arrays in R and Python and the implications for conversion and interoperability.</p>
</li>
</ul>
<h2>Why reticulate?</h2>
<p>From the <a rel="nofollow" href="https://en.wikipedia.org/wiki/Reticulated_python" target="_blank">Wikipedia</a> article on the reticulated python:</p>
<blockquote>
<p>The reticulated python is a speicies of python found in Southeast Asia. They are the world’s longest snakes and longest reptiles…The specific name, reticulatus, is Latin meaning “net-like”, or reticulated, and is a reference to the complex colour pattern.</p>
</blockquote>
<p>From the <a rel="nofollow" href="https://www.merriam-webster.com/dictionary/reticulate" target="_blank">Merriam-Webster</a> definition of reticulate:</p>
<blockquote>
<p>1: resembling a net or network; especially : having veins, fibers, or lines crossing a reticulate leaf. 2: being or involving evolutionary change dependent on genetic recombination involving diverse interbreeding populations.</p>
</blockquote>
<p>The package enables you to <em>reticulate</em> Python code into R, creating a new breed of project that weaves together the two languages.</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://blog.rstudio.com/2018/03/26/reticulate-r-interface-to-python/"> RStudio Blog</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/r-7YRR6NACY" height="1"></a></div>