I have had great use of rpy2, especially with the rnumpy and ipy_rnumpy 
wrappers. One useful feature of rnumpy [1] is autoconversion from Python to R 
objects, which will also deal with nested lists/dicts.

Is there an equally convenient way of getting a Python dict or list out of an R 
list, possibly nested? Consider this example:

from rnumpy import *
d = dict(i=123, x=0.25, s="test", nested=dict(j=456, t="nested list"))
r["y"] = rcopy(d)
r.str(r.y)

The output is:
List of 4
 $ i     : int 123
 $ x     : num 0.25
 $ s     : chr "test"
 $ nested:List of 2
  ..$ j: int 456
  ..$ t: chr "nested list"

Here, r.y is of <class 'rnumpy.RWrapper'>, whereas I would like to have the 
output as a native Python object. (In my actual use case, r.y would be the 
output of some R function, rather than corresponding to an existing Python dict 
8-)

The best I've been able to do is recurse through the names() of the R list, see 
code at end. It works for my simple example, but I'm not sure if it will work 
with more complicated structures. Comments are welcome.

Thank you in advance for any help.
Best regards,
Jon Olav Vik

[1] http://bitbucket.org/njs/rnumpy/wiki/Home
"More natural/smarter passing of Python objects to R (Python dicts map to R 
lists, Python lists have their contents autodetected and are mapped to boolean/
integral/numeric/character/list types as appropriate, numpy arrays are mapped 
correctly by default, etc.)"


Here's the code. (Replace ¤¤¤ with >>> to make the doctests work...I'm posting 
from Gmane, which believes >>> means top-posting.)

def rlist2pydict(x):
    """
    Convert an R named list to a Python dict, recursively.
    
    Example:
    ¤¤¤ from rnumpy import *
    ¤¤¤ d = dict(i=123, x=0.25, s="test", nested=dict(j=456, t="nested list"))
    ¤¤¤ r["y"] = rcopy(d)
    ¤¤¤ r.str(r.y) # the "NULL" at the end is because str() returns nothing
    List of 4
     $ i     : int 123
     $ x     : num 0.25
     $ s     : chr "test"
     $ nested:List of 2
      ..$ j: int 456
      ..$ t: chr "nested list"
    NULL
    ¤¤¤ rlist2pydict(r.y) == d
    True
    """
    xnames = r.names(x)
    if r.is_null(xnames):
        return x[0] if len(x) == 1 else list(x)
    else:
        return dict((k, rlist2pydict(r.dollar(x, k))) for k in xnames)



------------------------------------------------------------------------------
_______________________________________________
rpy-list mailing list
rpy-list@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/rpy-list

Reply via email to