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

泄露秘密 提交于 2019-12-11 08:08:44

问题


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)]


来源:https://stackoverflow.com/questions/46010397/rpy2-access-r-named-list-items-by-name-low-level-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!