This short blog post illustrates how easy it is to use R and Python in the same R Notebook thanks to the{reticulate}
package. For this to work, you might need to upgrade RStudio to the current preview version.Let’s start by importing {reticulate}
:
1 |
|
{reticulate}
is an RStudio package that provides “a comprehensive set of tools for interoperabilitybetween Python and R”. With it, it is possible to call Python and use Python libraries withinan R session, or define Python chunks in R markdown. I think that using R Notebooks is the best wayto work with Python and R; when you want to use Python, you simply use a Python chunk:
1 |
|
Fantastic!
However, if you wish to use Python interactively within your R session, you must start the PythonREPL with the repl_python()
function, which starts a Python REPL. You can then do whatever youwant, even access objects from your R session, and then when you exit the REPL, any object youcreated in Python remains accessible in R. I think that using Python this way is a bit more involvedand would advise using R Notebooks if you need to use both languages.
I installed the Anaconda Python distribution to have Python on my system. To use it with {reticulate}
I must first use the use_python()
function that allows me to set which version of Python I wantto use:
1 |
|
I can now load a dataset, still using R:
1 |
|
1 |
|
and now, to access the mtcars
data frame, I simply use the r
object:
1 |
|
1 |
|
.describe()
is a Python Pandas DataFrame method to get summary statistics of our data. This means thatmtcars
was automatically converted from a tibble
object to a Pandas DataFrame! Let’s check its type:
1 |
|
1 |
|
Let’s save the summary statistics in a variable:
1 |
|
Let’s access this from R, by using the py
object:
1 |
|
1 |
|
Let’s try something more complex. Let’s first fit a linear model in Python, and see how R sees it:
1 |
|
1 |
|
Just for fun, I ran the linear regression with the Scikit-learn library too:
1 |
|
1 |
|
1 |
|
1 |
|
Let’s access the model
variable in R and see what type of object it is in R:
1 |
|
1 |
|
So because this is a custom Python object, it does not get converted into the equivalent R object.This is described here. However, you can stilluse Python methods from within an R chunk!
1 |
|
1 |
|
1 |
|
1 |
|
I must say that I am very impressed with the {reticulate}
package. I think that even if you areprimarily a Python user, this is still very interesting to know in case you need a specific functionfrom an R package. Just write all your script inside a Python Markdown chunk and then use the Rfunction you need from an R chunk! Of course there is also a way to use R from Python, a Python librarycalled rpy2
but I am not very familiar with it. From what I read, it seems to be also quitesimple to use.
Hope you enjoyed! If you found this blog post useful, you might want to followme on twitter for blog post updates andbuy me an espresso or paypal.me.