Python Pandas to R dataframe

JonghoKim picture JonghoKim · Jun 7, 2014 · Viewed 18.3k times · Source

I am going to convert Python pandas dataframe to dataframe in R. I found out few libraries for this problem

http://pandas.pydata.org/pandas-docs/stable/r_interface.html

which is rpy2

But I couldn't find the methods for saving or transfer it to R.

Firstly I tried "to_csv"

df_R = com.convert_to_r_dataframe(df_total)
df_R.to_csv(direc+"/qap/detail_summary_R/"+"distance_"+str(gp_num)+".csv",sep = ",")

But it gives me an error

"AttributeError: 'DataFrame' object has no attribute 'to_csv'  "

So I tried to see its data type it was

<class 'rpy2.robjects.vectors.DataFrame'>

how could I save this type object to csv file or transfer to R?

Answer

lgautier picture lgautier · Jun 7, 2014

The recent documentation https://rpy2.github.io/doc/v3.2.x/html/generated_rst/pandas.html has a section about interacting with pandas.

Otherwise objects of type rpy2.robjects.vectors.DataFrame have a method to_csvfile, not to_csv:

https://rpy2.github.io/doc/v3.2.x/html/vector.html#rpy2.robjects.vectors.DataFrame.to_csvfile

If wanting to pass data between Python and R, there are more efficient ways than writing and reading CSV files. Try the conversion system:

from rpy2.robjects import pandas2ri
pandas2ri.activate()

from rpy2.robjects.packages import importr

base = importr('base')
# call an R function on a Pandas DataFrame
base.summary(my_pandas_dataframe)