-->

Prepare a python string for R using rpy2

2020-02-13 07:19发布

问题:

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)