Using R data and functions with rpy2 in Python:
Import and activate the environment:
from rpy2.robjects import r, pandas2ri
pandas2ri.activate()
Get R dataframe: rdf = r.iris.head()
or rdf = r['iris'].head()
.
List all methods and properties of the dataframe with dir(r.iris)
.
Convert R dataframe to Pandas dataframe: pdf = pandas2ri.ri2py(rdf)
.
Use R function: r.mean
or mean = r['mean']
.
Convert Pandas dataframe to R dataframe and feed to R function:
res = mean(pandas2ri.py2ri(pdf['Sepal.Length']))
.
Evaluating strings as R code: ```
r('mydata <- head(iris)') r('mean(mydata$Sepal.Length)') ``
Ref: