R from python

Open In Colab

R from python#

Python has an R api called Rpy2. You can install it with conda install rpy2 or pip install rpy2. We’ll just cover some really basic examples.

import rpy2
import rpy2.rinterface as ri
import rpy2.robjects as ro
from rpy2.robjects.packages import importr

#ri.initr()

The robjects sub-library contains the simplest variation of the interface. Here’s an example of executing R code in a python session.

z = ro.r('''
     x = matrix(1 : 10, 5, 2)
     y = matrix(11 : 20, 5, 2)
     x + y;
     ''')
print(z)
     [,1] [,2]
[1,]   12   22
[2,]   14   24
[3,]   16   26
[4,]   18   28
[5,]   20   30

You can then operate on this matrix in python. Here’s an example where we import the plotting library and use it.

base = ro.packages.importr('base')
base.rowSums(z)
FloatVector with 5 elements.
34.000000 38.000000 42.000000 46.000000 50.000000

Here’s an example of defining a function in R and using it in python.

fishersz = ro.r('function(r) .5 * log((1 + r) / (1 - r))')
fishersz(.7)
FloatVector with 1 elements.
0.867301