在rpy2> = 3.0.0中,有没有办法从R向量,矩阵等返回名称

Chr*_*rek 5 rpy2 python-3.x

我想从命名的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]
Run Code Online (Sandbox Code Playgroud)

但是在rpy2> = 3.0.0中,输出将转换为numpy数组,因此当然没有.names或.rx,因此名称似乎丢失了。

>>> stats.quantile(numpy.array([1,2,3,4]))
array([1.  , 1.75, 2.5 , 3.25, 4.  ])
Run Code Online (Sandbox Code Playgroud)

lga*_*ier 1

rpy23.0.0 正在尝试简化其转换系统,从而使其缺陷更容易预测和减轻。

在这里,当 numpy 转换层处于活动状态时发生的情况是:

  • 每当 R 需要时,numpy 数组都会转换为 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)
Run Code Online (Sandbox Code Playgroud)

然后可以在我们需要时使用该自定义转换:

with conversion.localconverter(myconverter):
    res = stats.quantile(numpy.array([1, 2, 3, 4]))
Run Code Online (Sandbox Code Playgroud)

结果是:

>>> print(res.names)                                                                                                   
[1] "0%"   "25%"  "50%"  "75%"  "100%"
Run Code Online (Sandbox Code Playgroud)

如果这看起来太费力,您还可以完全跳过 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%']
Run Code Online (Sandbox Code Playgroud)