CommunityData:Exporting from Python to R

From CommunityData

I run a cell like this at the top:

# import code to write r modules and create our variable we'll write to
import rpy2.robjects as robjects
from rpy2.robjects import pandas2ri
pandas2ri.activate()
r = {}
def remember(name, x):
    r[name] = x
    display(x)
#save the r function to rdata file
def save_to_r(r_dict, filename="output.RData"):
    for var_name, x in r.items():
        var_name = var_name.replace('_', '.')
        if type(x) == numpy.int64:
            x = np.asscalar(x)
        if type(x) == pd.DataFrame:
            rx = pandas2ri.py2ri(x)
        else:
            rx = x
        robjects.r.assign(var_name, x)
        # create a new variable called in R
    robjects.r("r <- sapply(ls(), function (x) {eval(parse(text=x))})")
    robjects.r('save("r", file="{}")'.format(filename))
    robjects.r("rm(list=ls())")

At the end, I save the file in the normal way:

save_to_r(r, "network_data.RData")