rpy2 - how to save dataframe as RData file to disk?

Viewed 1548

I am wondering how to save a pandas dataframe to an .RData file, How can I save to an RData from from a pandas dataframe? I have everything up to the last step here:

import pandas as pd
import rpy2
from rpy2 import robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()

# load RData file
df = pandas2ri.ri2py(robjects.r['get'](robjects.r['load'](path_to_rdata_file)))

.... do some processing to df ...

# save df as RData file
r_df = pandas2ri.py2ri(df)
??????????

How can I save the pandas data to disk as an .RData file?

1 Answers

I finally figured out the answer, here is how you write to .RData file using a pandas dataframe:

First convert dataframe to R dataframe:

r_data = pandas2ri.py2ri(df)

Then we have to assign the dataframe to a variable in the "R workspace":

robjects.r.assign("my_df", r_data)

Finally, we can reference the variable by name in order to call the save command:

robjects.r("save(my_df, file='{}')".format(filename))

Here are 2 helper functions if you want to read/write RData files but work in python with pandas:

# 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))
    os.chmod(filename, 0o777)
Related