Converting an RPy2 ListVector to a Python dictionary

前端 未结 7 1213
日久生厌
日久生厌 2020-12-09 16:46

The natural Python equivalent to a named list in R is a dict, but RPy2 gives you a ListVector object.

import rpy2.robjects as robjects

a = robjects.r(\'list         


        
7条回答
  •  情歌与酒
    2020-12-09 17:38

    I think to get a r vector into a dictionary does not have to be so involving, how about this:

    In [290]:
    
    dict(zip(a.names, list(a)))
    Out[290]:
    {'fizz': 
    [123.000000],
     'foo': 
    ['barbat']}
    In [291]:
    
    dict(zip(a.names, map(list,list(a))))
    Out[291]:
    {'fizz': [123.0], 'foo': ['barbat']}
    

    And of course, if you don't mind using pandas, it is even easier. The result will have numpy.array instead of list, but that will be OK in most cases:

    In [294]:
    
    import pandas.rpy.common as com
    com.convert_robj(a)
    Out[294]:
    {'fizz': [123.0], 'foo': array(['barbat'], dtype=object)}
    

提交回复
热议问题