views:

135

answers:

3

Hello guys, I'm having some trouble to understand the mapping with rpy2 object and python object.

I have a function(x) which return a tuple object in python, and i want to map this tuple object with R object list or vector.

First, i'm trying to do this :

# return a python tuple into this r object tlist
robjects.r.tlist = get_max_ticks(x) 

#Convert list into dataframe
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')

FAIL with error : rinterface.RRuntimeError: Error in eval(expr, envir, enclos) : object 'tlist' not found

So i'm trying an other strategy :

robjects.r["tlist"]  = get_max_ticks(x)
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')

FAIL with this error : TypeError: 'R' object does not support item assignment

Could you help me to understand ? Thanks a lot !!

+2  A: 

Use globalEnv:

import rpy2.robjects as ro
r=ro.r

def get_max_ticks():
    return (1,2)
ro.globalEnv['tlist'] = ro.FloatVector(get_max_ticks())
r('x <- as.data.frame(tlist,row.names=c("seed","ticks"))')
print(r['x'])
#       tlist
# seed      1
# ticks     2

It may be possible to access symbols in the R namespace with this type of notation: robjects.r.tlist, but you can not assign values this way. The way to assign symbol is to use robject.globalEnv.

Moreover, some symbols in R may contain a period, such as data.frame. You can not access such symbols in Python using notation similar to robjects.r.data.frame, since Python interprets the period differently than R. So I'd suggest avoiding this notation entirely, and instead use robjects.r['data.frame'], since this notation works no matter what the symbol name is.

unutbu
This notation is not safe either, as doing something like "ro.globalEnv['data.frame'] = ro.r('function(x) NULL')" somewhere before will cause problem.I recommend using the class DataFrame.
lgautier
Thx @~unutbu, thx @lgautier for your response here and on mailling list, now i'm trying to understand example with data.frame object in manual
reyman64
A: 

You could also avoid the assignment in R all together:

import rpy2.robjects as ro
tlist = ro.FloatVector((1,2))
keyWordArgs = {'row.names':ro.StrVector(("seed","ticks"))}
x = ro.r['as.data.frame'](tlist,**keyWordArgs)
ro.r['print'](x)
Mark
+2  A: 

Read The Fine Manual

lgautier