简体   繁体   中英

modifying r code based on values of python in rpy2?

I'm trying to modify a row in R based on values stored & calculated in python. Here is the code I've used:

def create_new_row_r(json_dict):
    newdata = robjects.r('''
                         createdata = function(row){
                             dummydata <- row
                             dummydata["field1"] <- %s
                             dummydata["field2"] <- %s
                             dummydata["field3"] <- %i
                             dummydata["field4"] <- %s
                             dummydata["field5"] <- %i
                             dummydata["field6"] <- %s
                             dummydata["field7"] <- %i
                             dummydata["field8"] <- %i
                             dummydata["field8"] <- %i
                             dummydata["field9"] <- %i
                             dummydata["field10"] <- %i
                             dummydata["field11"] <- %i
                             return(dummydata)
                         }
                         createdata(datz1[1,])
                         '''
                         %(json_dict["field1"],   json_dict["field2"], json_dict["field3"], 
                           json_dict["field4"], json_dict["field5"], 
                           json_dict["field6"], json_dict["field7"], json_dict["field8"], 
                           json_dict["field9"], json_dict["field10"], 
                           json_dict["field11"], json_dict["field12"]))
    print "new row assembled"
    return newdata

I then call this function & pass in a json_dict which contains those values & data types. I'm expecting this to return the robject "dummydata" as detailed in the rpy2 "running r code" documentation here:

http://rpy.sourceforge.net/rpy2/doc-dev/html/introduction.html

but this code isn't working or throwing any errors (other than causing the API i'm running it on to crash when it is called)

Is it possible to do this? Have I messed up the code somewhere? is there a better way to accomplish this?

Thanks, will upvote

For the string fields, you need to use %r because %s will not add quotes for your strings.

You could also use json.dumps()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM