Mapping python tuples and R list using rpy2?

I'm having trouble understanding the mapping to the rpy2 object and the python object.

I have a function (x) that returns a tuple object in python, and I want to map this tuple object using a list or object vector R.

First I try 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, enc): object 'tlist' not found

So I'm trying to use a different strategy:

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

This error fails: TypeError: object 'R' does not support element assignment

Could you help me understand? Many thanks!

+4
source share
2 answers

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 

Symbols in the R namespace can be accessed using this type of notation: robjects.r.tlist , but you cannot assign values ​​this way. A way to assign a character is to use robject.globalEnv .

In addition, some characters in R may contain a period, such as data.frame . You cannot access such characters in Python using a notation similar to robjects.r.data.frame , since Python interprets the period differently than R Therefore, I propose to completely exclude this notation and use robjects.r['data.frame'] instead, since this notation works regardless of the symbol name.

+3
source

You can also avoid assigning to R 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) 
0
source

Source: https://habr.com/ru/post/1316433/


All Articles