Question

I'm just starting to learn how to use rpy2 with python. I'm able to make simple plots and such, but I've run into the problem that many options in R use ".". For example, here's an R call that works:

barplot(t, col=heat.colors(2), names.arg=c("pwn", "pwn2"))

where t is a matrix.

I want to use the same call in python, but it rejects the "." part of names.arg. My understanding was that in python you replace the "." with "_", so names_arg for example, but that is not working either. I know this is a basic problem so I hope someone has seen this and knows the fix. Thanks!

Was it helpful?

Solution

You can use a dictionary here for the named arguments (using **) as described in the docs, and call R directly for the functions. Also remember that RPy2 expects its own vector objects. Yes, it's a bit awkward, but on the plus side, you should be able to do anything in rpy2 you could do in R.

from rpy2 import robjects
color = robjects.r("heat.colors")()
names = robjects.StrVector(("pwn", "pwn2"))
robjects.r.barplot(t, col=color, **{"names.arg":names})

(Note that this is for rpy2 version 2.0.x; there are some changes in the unreleased 2.1 which I haven't had a chance to look at yet.)

OTHER TIPS

I don't know whether Rpy will accept this, but you can have keyword parameters with periods in them. You have to pass them through a dictionary though. Like this:

>>> def f(**kwds): print kwds
... 
>>> f(a=5, b_c=6)
{'a': 5, 'b_c': 6}
>>> f(a=5, b.c=6)
Traceback (  File "<interactive input>", line 1
SyntaxError: keyword cant be an expression (<interactive input>, line 1)
>>> f(**{'a': 5, 'b.c': 6})
{'a': 5, 'b.c': 6}

With rpy2-2.1.0, one way to write it would be:

from rpy2.robjects.packages import importr
graphics = importr("graphics")
grdevices = importr("grDevices")

graphics.barplot_default(t, 
                         col = grdevices.heat_colors(2),
                         names_arg = StrVector(("pwn", "pwn2")))

Having to use barplot_default (rather that barplot) is due to the extensive use of the ellipsis '...' in R'sfunction signatures and to the fact that save parameter name translation would require analysis of the R code a function contains.

More, and an example of a function to perform systematic translation of '.' to '_' is at: http://rpy.sourceforge.net/rpy2/doc-2.1/html/robjects.html#functions

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top