pandas df to R df code example
Example 1: pandas df to R df
In [1]: from rpy2.robjects import r, pandas2ri
In [2]: pandas2ri.activate()
Example 2: pandas df to R df
In [5]: df = pd.DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7,8,9]},
...: index=["one", "two", "three"])
...:
In [6]: r_dataframe = pandas2ri.py2ri(df)
In [7]: print(type(r_dataframe))
<class 'rpy2.robjects.vectors.DataFrame'>
In [8]: print(r_dataframe)
A B C
one 1 4 7
two 2 5 8
three 3 6 9
Example 3: pandas df to R df
In [3]: r.data('iris')
Out[3]:
R object with classes: ('character',) mapped to:
<StrVector - Python:0x12a3f3f08 / R:0x7f896c23cf38>
['iris']
In [4]: r['iris'].head()
Out[4]:
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa