RPy2 substitute function does not work

I’m using rpy2 to call R package from Python, which works pretty well most of the time. Yet, I’ve encountered an issue with the R function called substitute that do not behave as expected when called from rpy2. Consider the following R function that uses substitute to print the name of the argument called arg1 (not its content). Let us suppose that arg1 is a float, which value equals 1.

test_substitute <-
        # do something with arg1

Then, you can call the function from an R interface. It should behave as follows (The >>> signs indicates the prompt):

>>> a<-1
>>> test_substitute(a)
[1] 1

Now, in python, using RPY2, you will use the following code (assuming your R function is in the package Test::

>>> # importing the R function
>>> from rpy2 import robjects
>>> from rpy2.robjects.packages import importr
>>> Test = importr("Test") 
>>> a= 1.
>>> print Test.test_substitute(a)
[1] 1
[1] 1

The function prints the contents of a and not its name (we expected “a” as in the R interface)

Now, I don’t know any perfect solution, but from the Rpy2 documentation, I’ve seen on the

robjects formulae.html page some usage of robjects.r that could be useful and indeed, it makes the trick. Here is a solution.

You can create a function using robject.r :

>>> f = robjects.r('test_substitute')
>>> a = 1.
>>> f(a)
[1] 1
[1] 1

Yet, this does not work either, you need to create the R code an call it using robjects.r

>>> a = 1.
>>> robjects.r('a<-1; test_substitute(%s)' % 'a')
[1] 1
Please follow and like us:
This entry was posted in Computer Science and tagged , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.