[英]Mapping python tuple and R list with rpy2?
I'm having some trouble to understand the mapping with rpy2 object and python object. 我在理解rpy2对象和python对象的映射时遇到了一些麻烦。
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. 我有一个函数(x)在python中返回一个元组对象,我想用R对象列表或向量映射这个元组对象。
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 失败的错误:rinterface.RRuntimeError:eval中的错误(expr,envir,enclos):找不到对象'tlist'
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 失败并出现此错误:TypeError:'R'对象不支持项目分配
Could you help me to understand ? 你能帮我理解吗? Thanks a lot !! 非常感谢 !!
Use globalEnv
: 使用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. 可以使用这种表示法访问R
名称空间中的符号: robjects.r.tlist
,但不能以这种方式分配值。 The way to assign symbol is to use robject.globalEnv
. 分配符号的方法是使用robject.globalEnv
。
Moreover, some symbols in R
may contain a period, such as data.frame
. 此外, R
某些符号可能包含句点,例如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
. 您不能使用类似于robjects.r.data.frame
符号在Python中访问此类符号,因为Python以不同于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. 所以我建议完全避免使用这种表示法,而是使用robjects.r['data.frame']
,因为无论符号名称是什么,这种表示法都有效。
You could also avoid the assignment in R all together: 你也可以避免R中的任务一起:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.