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 !!
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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.