CommunityData:Exporting from Python to R: Difference between revisions

From CommunityData
No edit summary
No edit summary
 
Line 9: Line 9:
     r[name] = x
     r[name] = x
     display(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")

Latest revision as of 21:35, 25 August 2016

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")