简体   繁体   English

修改基于rpy2中python值的r代码?

[英]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. 我试图根据在python中存储和计算的值修改R中的一行。 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. 然后,我调用此函数并传入包含这些值和数据类型的json_dict。 I'm expecting this to return the robject "dummydata" as detailed in the rpy2 "running r code" documentation here: 我期望这将返回robject“ dummydata”,如rpy2“运行r代码”文档中所述:

http://rpy.sourceforge.net/rpy2/doc-dev/html/introduction.html 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) 但是此代码无法正常工作或引发任何错误(除了使我正在运行的API在被调用时崩溃)

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. 对于字符串字段,您需要使用%r因为%s不会为字符串添加引号。

You could also use json.dumps() 您也可以使用json.dumps()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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