Rpy2 Made Easy

A consolidated guide at using Rpy2 for beginners

Sreyasha
Analytics Vidhya
3 min readOct 14, 2020

--

Two data scientists walked into a bar. Both of them wanted to use R from Python. Lo and behold — Rpy2.

Rpy2 (R’s embed in python) can be pretty intimidating to use and solely because it’s not as well fleshed out as its individual parts. Also because it is much easier to use R and python by themselves, but certain software architectures might require a consolidation of the two. Python’s intuitive data structures, visual libraries and great IDE’s mixed with R’s trusted packages make for a solid resource for a data scientist’s exploitation.

How to Setup

  1. Download Python3+ and R, if you haven’t already.
  2. Install the Rpy2 from here

Using R packages and function from Python

The following example below shows how to call existing R functions from python using appropriate packages. The imports to be made are the following:

The below snippet shows how to import R objects and packages to python. The time series object and forecast package from R are used in the example. One needs to make sure these functionalities/packages work fine in R separately.

Time to use functions from forecast package in python:

The variable “forecasted_arima” is a List Vector, an R datatype. One can print the columns names to find the desired columns. The following lines can be used to find the forecasted result:

Alternatively, one can access the columns with their names as follows:

Calling Existing R functions from Python

Suppose, one has a R code as follows:

The call the above forecast function from python, the following import needs to be made:

The above step makes the R function available from python. It can be accessed by:

Conclusion

There are many other ways Rpy2 can be used in a python framework, including ways to write R code in python itself. However those are more prone to error that the ones elucidated here.

Working with both R and Python are done regularly by data scientists, and an interface to embed one on the other is truly powerful if used well. Despite it not being very popular, rpy2 can provide technical edge to data scientists and developers alike while designing and integrating a holistic systems.

Please read the rpy2 documentation thoroughly here.

--

--