<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/run-python-from-r/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://www.listendata.com/2018/03/run-python-from-r.html"> ListenData</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div dir="ltr">This article explains how to call or run python from R. Both the tools have its own advantages and disadvantages. It’s always a good idea to use the best packages and functions from both the tools and combine it. In data science world, these tools have a good market share in terms of usage. R is mainly known for data analysis, statistical modeling and visualization. While python is popular for deep learning and natural language processing.
<p>In recent KDnuggets Analytics software survey poll, Python and R were ranked top 2 tools for data science and machine learning. If you really want to boost your career in data science world, these are the languages you need to focus on.</p>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i1.wp.com/4.bp.blogspot.com/-IRvspjqP-og/WrpZqbx_N_I/AAAAAAAAHKc/AKjcx3tBmiUXT_9PVS9uwVu-6TC-802GgCLcBGAs/s1600/python_R_datascience.PNG?ssl=1" target="_blank"><img border="0" data-original-height="224" src="https://i1.wp.com/4.bp.blogspot.com/-IRvspjqP-og/WrpZqbx_N_I/AAAAAAAAHKc/AKjcx3tBmiUXT_9PVS9uwVu-6TC-802GgCLcBGAs/s1600/python_R_datascience.PNG?resize=450%2C224&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Combine Python and R</td>
</tr>
</tbody>
</table>
<p>RStudio developed a package called <b>reticulate</b> which provides a medium to run Python packages and functions from R.</p>
<p><b><span>Install and Load Reticulate Package</span></b></p>
<p>Run the command below to get this package installed and imported to your system.</p>
<blockquote><p># Install reticulate package<br>install.packages(“reticulate”)</p>
<p># Load reticulate package<br>library(reticulate)</p></blockquote>
<p></p>
<div>
<div><b><span>Check whether Python is available on your system</span></b></div>
<div>
<blockquote><p>py_available()</p></blockquote>
</div>
</div>
<div>It returns TRUE/FALSE. If it is TRUE, it means python is installed on your system.
<p><b><span>Import a python module within R</span></b></p>
<p>You can use the function <b>import( ) </b>to import a particular package or module.</p>
<blockquote><p>os &lt;-import(“os”)<br>os$getcwd()</p></blockquote>
<div>The above program returns working directory.</div>
<pre>[1] &quot;C:\\Users\\DELL\\Documents&quot;<br></pre>
<p>You can use <b>listdir( ) </b>function from <b>os</b> package<b> </b>to<b> </b>see all<b> </b>the files in working directory</p>
<blockquote><p>os$listdir()</p></blockquote>
<pre> [1] &quot;.conda&quot;                       &quot;.gitignore&quot;                   &quot;.httr-oauth&quot;                 <br>  [4] &quot;.matplotlib&quot;                  &quot;.RData&quot;                       &quot;.RDataTmp&quot;                   <br>  [7] &quot;.Rhistory&quot;                    &quot;1.pdf&quot;                        &quot;12.pdf&quot;                      <br> [10] &quot;122.pdf&quot;                      &quot;124.pdf&quot;                      &quot;13.pdf&quot;                      <br> [13] &quot;1403.2805.pdf&quot;                &quot;2.pdf&quot;                        &quot;3.pdf&quot;                       <br> [16] &quot;AIR.xlsx&quot;                     &quot;app.r&quot;                        &quot;Apps&quot;                        <br> [19] &quot;articles.csv&quot;                 &quot;Attrition_Telecom.xlsx&quot;       &quot;AUC.R&quot;             <br></pre>
<p><b><span>Install Python Package</span></b></p>
<p><b>Step 1 : Create a new environment </b></p>
<blockquote><p>conda_create(“r-reticulate”)</p></blockquote>
<p><b>Step 2 : Install a package within a conda environment</b></p>
<blockquote><p>conda_install(“r-reticulate”, “numpy”)</p></blockquote>
<p><i><span><b>Since numpy is already installed, you don’t need to install it again. The above example is just for demonstration.</b></span></i></p>
<p><b>Step 3 : Load the package</b></p>
<blockquote><p>numpy &lt;-import(“numpy”)</p></blockquote>
<div></div>
<div><b><span>Working with numpy array</span></b></div>
<p>Let’s create a sample numpy array</p>
<blockquote><p>y &lt;-array(1:4, c(2, 2))<br>x &lt;-<b>numpy</b>$array(y)</p></blockquote>
<pre>     [,1] [,2]<br>[1,]    1    3<br>[2,]    2    4<br></pre>
<p><b><span>Transpose the above array</span></b></p>
<blockquote><p>numpy$transpose(x)</p></blockquote>
<pre>    [,1] [,2]<br>[1,]    1    2<br>[2,]    3    4<br></pre>
<p><b><span>Eigenvalues and eigen vectors</span></b></p>
<blockquote><p>numpy$linalg$eig(x)</p></blockquote>
<pre>[[1]]<br>[1] -0.3722813  5.3722813<br><br>[[2]]<br>           [,1]       [,2]<br>[1,] -0.9093767 -0.5657675<br>[2,]  0.4159736 -0.8245648<br></pre>
<p><b><span>Mathematical Functions</span></b></p>
<blockquote><p>numpy$sqrt(x)<br>numpy$exp(x)</p></blockquote>
<p><b><span>Working with Python interactively</span></b></p>
<div></div>
<div>You can create an interactive Python console within R session. Objects you create within Python are available to your R session (and vice-versa).</div>
<div></div>
<div>
<div>By using <code>repl_python()</code> function, you can make it interactive. Download the <a rel="nofollow" href="https://sites.google.com/site/pocketecoworld/AIR.xlsx" target="_blank"><b>dataset</b> </a>used in the program below.</div>
<blockquote>
<div>
<div>repl_python()</div>
<div></div>
<div># Load Pandas package</div>
<div>import pandas as pd</div>
<div></div>
<div># Importing Dataset</div>
<div>travel = pd.read_excel(“AIR.xlsx”)</div>
</div>
<div># Number of rows and columns<br>travel.shape
<p># Select random no. of rows<span>	</span><br>travel.sample(n = 10)</p>
<p># Group By<br>travel.groupby(“Year”).AIR.mean()</p>
<p># Filter<br>t = travel.loc[(travel.Month >= 6) &amp; (travel.Year >= 1955),:]</p>
<p># Return to R<br>exit</div>
</blockquote>
</div>
</div>
<p><span>Note : You need to enter <b>exit</b> to return to the R environment.</span></p>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i2.wp.com/2.bp.blogspot.com/-y4YEwqQOMww/WrpPJUtR1OI/AAAAAAAAHKM/iQPF5T4CSs8ZUoBhup64sgjQt9dvI_rfwCLcBGAs/s1600/python_R.PNG?ssl=1" target="_blank"><img border="0" src="https://i2.wp.com/2.bp.blogspot.com/-y4YEwqQOMww/WrpPJUtR1OI/AAAAAAAAHKM/iQPF5T4CSs8ZUoBhup64sgjQt9dvI_rfwCLcBGAs/s1600/python_R.PNG?resize=450%2C317&ssl=1" data-original-width="450" alt="call python from R" data-original-height="317" title="" data-recalc-dims="1"></a></td>
</tr>
<tr>
<td>Run Python from R</td>
</tr>
</tbody>
</table>
<p><b><span>How to access objects created in python from R</span></b></p>
<p>You can use the <b>py</b> <b>object</b> to access objects created within python.</p>
<blockquote><p>summary(py$t)</p></blockquote>
<p>In this case, I am using R’s <b>summary( ) function</b> and accessing dataframe <b>t </b>which was created in python. Similarly, you can create line plot using ggplot2 package.</p>
<blockquote><p># Line chart using ggplot2<br>library(ggplot2)<br>ggplot(py$t, aes(AIR, Year)) + geom_line()</p></blockquote>
<div></div>
<div><b><span>How to access objects created in R from Python</span></b>
<div></div>
<div>You can use the <b>r object </b>to accomplish this task.<b> </b></div>
<div></div>
<div><b>1. Let’s create a object in R</b></div>
<blockquote><p>mydata = head(cars, n=15)</p></blockquote>
<p><b>2. Use the R created object within Python REPL</b></p>
<blockquote><p>repl_python()<br>import pandas as pd<br><b>r.</b>mydata.describe()<br>pd.isnull(<b>r.</b>mydata.speed)<br>exit</p></blockquote>
</div>
<div></div>
<div><b><span>Building Logistic Regression Model using sklearn package</span></b></div>
<div></div>
<div>The sklearn package is one of the most popular package for machine learning in python. It supports various statistical and machine learning algorithms.</div>
<blockquote>
<div>repl_python()</div>
<div></div>
<div>
<div># Load libraries</div>
<div>from sklearn import datasets</div>
<div>from sklearn.linear_model import LogisticRegression</div>
<div></div>
<div># load the iris datasets</div>
<div>iris = datasets.load_iris()</div>
<div></div>
<div># Developing logit model</div>
<div>model = LogisticRegression()</div>
<div>model.fit(iris.data, iris.target)</div>
<div></div>
<div># Scoring</div>
<div>actual = iris.target</div>
<div>predicted = model.predict(iris.data)</div>
<div></div>
<div># Performance Metrics</div>
<div>print(metrics.classification_report(actual, predicted))</div>
<div>print(metrics.confusion_matrix(actual, predicted))</div>
</div>
</blockquote>
<div><b><span>Other Useful Functions</span></b></div>
<p><b><span>To see configuration of python</span></b></p>
<p>Run the <b>py_config( ) </b>command<b> </b>to find the version of R installed on your system.It also shows details about anaconda and numpy. </p>
<div>
<blockquote><p>py_config()</p></blockquote>
</div>
<pre>python:         C:\Users\DELL\ANACON~1\python.exe<br>libpython:      C:/Users/DELL/ANACON~1/python36.dll<br>pythonhome:     C:\Users\DELL\ANACON~1<br>version:        3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:25:24) [MSC v.1900 64 bit (AMD64)]<br>Architecture:   64bit<br>numpy:          C:\Users\DELL\ANACON~1\lib\site-packages\numpy<br>numpy_version:  1.14.2</pre>
<div>
<p><b><span>To check whether a particular package is installed</span></b></p>
<p>In the following program, we are checking whether <b>pandas </b>package is installed or not.</p>
<blockquote><p>py_module_available(“pandas”)</p></blockquote>
</div>
</div>
<div><span> About Author:</span> 
<p>Deepanshu founded ListenData with a simple objective – Make analytics easy to understand and follow. He has over 7 years of experience in data science and predictive modeling. During his tenure, he has worked with global clients in various domains.</p>
<p>Let's Get Connected: <a rel="nofollow" href="https://www.linkedin.com/in/deepanshubhalla" target="_blank">LinkedIn</a></p>
</div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://www.listendata.com/2018/03/run-python-from-r.html"> ListenData</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/w3bLeFN_Sfc" height="1"></a></div>