Prepare a python string for R using rpy2

女生的网名这么多〃 提交于 2019-11-28 06:49:04

问题


This question relates to python variable to R and perhaps also to this python objects to rpy2 but none of the two completely overlaps and the first one is actually unanswered.

My question is actually very simple. I have a string, say:

In [21]: strg
Out[21]: 'I want to go home'

and I want to pass it to R through robjects.r(''' ''') like this, for example:

robjects.r('''

test <- gsub("to", "",strg)

''')

but of course, when I run this I obtain: Error in gsub("me", "", strg) : object 'strg' not found.

I have not used rpy2 much (as obvious) but I guess is related to the environments in which R and Python see the objects.

I have tried a few things, like transforming the string strg to an robject first and then feed it to robjects.r(''' ''') but I get the same error message. Overall, I do not know how do this so that strg is seen at the R environment.

Any help is much appreciated!

Thanks in advance for your time!


回答1:


Just add the strg value to the command string:

robjects.r('''

test <- gsub("to", "",''' + strg + ''')

''')

or, by using .format:

robjects.r('''

test <- gsub("to", "",%s)

'''.format(strg))

Do note that you'll need to watch out for backslashes, see the question here




回答2:


I'd recommend you to create an function, as the R function exposed by rpy2 can be called just as if it was a Python function.

my_func = robjects.r('''
function(strg) {
    test <- gsub("to", "",strg)
    test
}
''')

my_func(strg)


来源:https://stackoverflow.com/questions/30754885/prepare-a-python-string-for-r-using-rpy2

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!