pandas 0.9.0 documentation

rpy2 / R interface


This is all highly experimental. I would like to get more people involved with building a nice RPy2 interface for pandas

If your computer has R and rpy2 (> 2.2) installed (which will be left to the reader), you will be able to leverage the below functionality. On Windows, doing this is quite an ordeal at the moment, but users on Unix-like systems should find it quite easy. rpy2 evolves in time and the current interface is designed for the 2.2.x series, and we recommend to use over other series unless you are prepared to fix parts of the code. Released packages are available in PyPi, but should the latest code in the 2.2.x series be wanted it can be obtained with:

# if installing for the first time
hg clone

cd rpy2
hg pull
hg update version_2.2.x
sudo python install


To use R packages with this interface, you will need to install them inside R yourself. At the moment it cannot install them for you.

Once you have done installed R and rpy2, you should be able to import pandas.rpy.common without a hitch.

Transferring R data sets into Python

The load_data function retrieves an R data set and converts it to the appropriate pandas object (most likely a DataFrame):

In [988]: import pandas.rpy.common as com

In [989]: infert = com.load_data('infert')

In [990]: infert.head()
  education  age  parity  induced  case  spontaneous  stratum  pooled.stratum
1    0-5yrs   26       6        1     1            2        1               3
2    0-5yrs   42       1        1     1            0        2               1
3    0-5yrs   39       6        2     1            0        3               4
4    0-5yrs   34       4        2     1            0        4               2
5   6-11yrs   35       3        1     1            1        5              32

Converting DataFrames into R objects

New in version 0.8.

Starting from pandas 0.8, there is experimental support to convert DataFrames into the equivalent R object (that is, data.frame):

In [991]: from pandas import DataFrame

In [992]: df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7,8,9]},
   .....:                index=["one", "two", "three"])

In [993]: r_dataframe = com.convert_to_r_dataframe(df)

In [994]: print type(r_dataframe)
<class 'rpy2.robjects.vectors.DataFrame'>

In [995]: print r_dataframe
      A B C
one   1 4 7
two   2 5 8
three 3 6 9

The DataFrame’s index is stored as the rownames attribute of the data.frame instance.

You can also use convert_to_r_matrix to obtain a Matrix instance, but bear in mind that it will only work with homogeneously-typed DataFrames (as R matrices bear no information on the data type):

In [996]: r_matrix = com.convert_to_r_matrix(df)

In [997]: print type(r_matrix)
<class 'rpy2.robjects.vectors.Matrix'>

In [998]: print r_matrix
      A B C
one   1 4 7
two   2 5 8
three 3 6 9

Calling R functions with pandas objects

High-level interface to R estimators