python-3.x - 有没有办法在 rpy2 >= 3.0.0 中从 R 向量、矩阵等返回名称

标签 python-3.x rpy2

我想将命名的 R 向量(或矩阵等)的名称返回到 Python 中。在 rpy2 < 3.0.0 中这是可能的,例如,

>>> stats.quantile(numpy.array([1,2,3,4]))
R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x7f3e664d6d88 / R:0x55c939a540c8>
[1.000000, 1.750000, 2.500000, 3.250000, 4.000000]
>>> stats.quantile(numpy.array([1,2,3,4])).names
R object with classes: ('character',) mapped to:
<StrVector - Python:0x7f3e66510788 / R:0x55c939a53648>
['0%', '25%', '50%', '75%', '100%']
>>> stats.quantile(numpy.array([1,2,3,4])).rx('25%')
R object with classes: ('numeric',) mapped to:
<FloatVector - Python:0x7f3e68770bc8 / R:0x55c938f23ba8>
[1.750000]

但是在 rpy2 >= 3.0.0 中,输出被转换为一个 numpy 数组,所以当然没有 .names 或 .rx ,因此名称似乎丢失了。
>>> stats.quantile(numpy.array([1,2,3,4]))
array([1.  , 1.75, 2.5 , 3.25, 4.  ])

最佳答案

rpy2 3.0.0 正试图简化其转换系统,从而使其更容易预测和减轻其缺陷。

在这里,当 numpy 转换层处于事件状态时发生的是:

  • numpy 数组会在 R
  • 需要时转换为 R 数组
  • 从 R
  • 返回时,R 数组被转换为 numpy 数组

    这种对称性不是必需的,而只是默认 numpy 转换层的方式。可以设置一个非对称转换层,在这里将 numpy 数组转换为 R 数组,但在从 R 返回时保留 R 数组,相对快速且容易。
    import numpy
    from rpy2.rinterface_lib import sexp
    from rpy2 import robjects
    from rpy2.robjects import conversion
    from rpy2.robjects import numpy2ri
    
    # We are going to build our custom converter by subtraction, that is
    # starting from the numpy converter and only revert the part converting R
    # objects into numpy arrays to the default conversion. We could have also
    # build it by addition. 
    myconverter = conversion.Converter('assym. numpy',
                                       template=numpy2ri.converter)
    myconverter.rpy2py.register(sexp.Sexp,
                                robjects.default_converter.rpy2py)
    

    然后可以在我们需要时使用该自定义转换:
    with conversion.localconverter(myconverter):
        res = stats.quantile(numpy.array([1, 2, 3, 4]))
    

    结果是:
    >>> print(res.names)                                                                                                   
    [1] "0%"   "25%"  "50%"  "75%"  "100%"
    

    如果这看起来太费力,您也可以完全跳过 numpy 转换器,仅使用默认转换器,并在您判断必要时手动将 numpy 数组转换为合适的 R 数组:
    >>> stats.quantile(robjects.vectors.IntVector(numpy.array([1, 2, 3, 4]))).names                                           
    R object with classes: ('character',) mapped to:
    ['0%', '25%', '50%', '75%', '100%']
    

    关于python-3.x - 有没有办法在 rpy2 >= 3.0.0 中从 R 向量、矩阵等返回名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54951506/

    相关文章:

    python-3.x - 如何使用命名绑定(bind)与 pandas 数据帧中的 cx_Oracle 中的批量插入 (executemany)

    带有 argparse 的 Python 单元测试

    python - rpy2(版本 2.3.10)——将 R 包中的数据导入 python

    python - 模块未找到错误 : No module named 'pandas.rpy'

    python - pickle 后如何更改类方法的定义

    Python Pygame 窗口没有响应

    python - 寻求更好的 Python 3.x+ 方法在一个函数中构建多个不同的 HTML

    python - 转换为 pandas 数据帧时保留 R 数据帧索引值

    python - 在 IPython 笔记本上使用 rpy2?

    python - 有没有办法在 python/rpy2 中访问 R 数据框列名?