开发者

Guidance in using rpy2 eval expression

I am new to both R and rpy2. I am trying to port the following example

library(MASS)  # for eqscplot  
data(topo, package="MASS")  
topo.kr <- surf.ls(2, topo)  
trsurf <- trmat(topo.kr, 0, 6.5, 0, 6.5, 50)  

to rpy2.

So far I have

import  rpy2.robjects as robjects
robjects.r('library(spatial)')  
f1 = robjects.r['surf.ls']  
x = robjects.IntVector([1,2,3])  
y开发者_开发问答 = robjects.IntVector([1,2,3])  
z = robjects.IntVector([1,30,3])  
res = f1(2, x,y,z)  

I assume that the result should be res. However when I print res using print(res.r_repr()) I get an expression which I am unable to evaluate. Would appreciate any help on this.


Then the question is more: how do I convert an R list to a Python dictionary (little to do with evaluating expressions). With rpy2-2.2.x (and 2.3-dev):

from rpy2.robjects.vectors import ListVector
# make an R list
l = ListVector({'a': 1, 'b': 'b'})

# get a Python dict out of an R list
dict(l.iteritems())


Your code works fine. I think you are just having trouble accessing the results. Your resulting "res" object is essentially an R list. I would convert it into the corresponding Python dictionary.

rListObj = {}
for key,val in zip(robjects.r.names(res),res):
  rListObj[key] = [i for i in val] #R Vector to List

Results in:

{'f': [1.0, 1.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 1.0, -1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0], 'rx': [1, 3], 'ry': [1, 3], 'np': [2], 'beta': [0.0, 0.0, 0.0, 0.0, 0.0, 0.0], 'r': [-1.7320508075688772, -1.6729239521451333e-16, -1.4142135623730951, -1.1547005383792512, -5.187907395343139e-17, -0.8164965809277259, -1.6729239521451333e-16, -1.4142135623730951, 3.415236843329339e-17, nan, -1.1547005383792512, -5.187907395343139e-17, -0.8164965809277259, nan, 0.0, -1.1547005383792512, -5.187907395343139e-17, -0.8164965809277259, nan, 0.0, 0.0], 'call': [<SignatureTranslatedFunction - Python:0xb7539dec / R:0xa686cec>, <IntVector - Python:0xb7534cac / R:0xa69e788>, <IntVector - Python:0xb7534d2c / R:0xa5f72f8>, <IntVector - Python:0xb7534c2c / R:0xa5f7320>, <IntVector - Python:0xb7534bac / R:0xa5f7348>], 'y': [1, 2, 3], 'x': [1, 2, 3], 'z': [1, 30, 3], 'wz': [0.0, 0.0, 0.0]}

I tested this against a somewhat old version of rpy2 (2.1.9), there are probably snazzier ways of doing this with more recent versions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜