Can I use rpy2 to save a pandas dataframe to an .Rdata file?
Here is how you write/read .RData
files with rpy2
(since accepted solution is deprecated and doesn't show how to save to .RData
file):
import rpy2
from rpy2 import robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()
# read .RData file as a pandas dataframe
def load_rdata_file(filename):
r_data = robjects.r['get'](robjects.r['load'](filename))
df = pandas2ri.ri2py(r_data)
return df
# write pandas dataframe to an .RData file
def save_rdata_file(df, filename):
r_data = pandas2ri.py2ri(df)
robjects.r.assign("my_df", r_data)
robjects.r("save(my_df, file='{}')".format(filename))
You can use rpy2 to do this. Once you have the data in a panda, you have to transmit it to R. This link provides an experimental interface between Python Pandas and R data.frames. A code example copied from the website:
from pandas import DataFrame
import pandas.rpy.common as com
df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6], 'C':[7,8,9]},
index=["one", "two", "three"])
r_dataframe = com.convert_to_r_dataframe(df)
print type(r_dataframe)
<class 'rpy2.robjects.vectors.DataFrame'>
print r_dataframe
A B C
one 1 4 7
two 2 5 8
three 3 6 9