-->

rpy2 access R named list items by name, low-level

2019-08-02 18:06发布

问题:

How do I access elements of a named list by name?

I have 3 functions, all of which return a ListSexpVector of class htest. One of them has 5 elements, ['method', 'parameter', 'statistic', 'p.value', 'data.name'], others have a different number, and order. I am interested in extracting the p.value, statistic and parameter from this list. In R I can use $, like so:

p.value <- fit$p.value
statistic <- fit$statistic
param <- fit$parameter

The best equivalent I found in rpy2 goes like:

p_val = fit[list(fit.do_slot('names')).index('p.value')]
stat  = fit[list(fit.do_slot('names')).index('statistic')]
param = fit[list(fit.do_slot('names')).index('parameter')]

Which is quite long-winded. Is there a better (shorter, sweeter, Pythonic) way?


There is the good-old-fashioned integer based indexing:

p_val = fit[3]
stat  = fit[2]
param = fit[1]

But it doesn't work when the positions are changed, and therefore is a serious limitation because I am fitting 3 different functions, and each return a different order.

回答1:

The high-level interface is meant to provide a friendlier interface as the low-level interface is quite close to R's C-API. With it one can do:

p_val = fit.rx2('p.value')

or

p_val = fit[fit.names.index('p.value')]

If working with the low-level interface, you will essentially have to implement your own convenience wrapper to reproduce these functionalities. For example:

def dollar(obj, name):
    """R's "$"."""
    return obj[fit.do_slot('names').index(name)]


标签: rpy2