尝试使用rpy2访问Python中的R类方法和字段

问题描述

我正在使用rpy2从CRAN存储库中导入一个名为“ MatrixEQTL”的库,以便使用importr在Python中运行,这是我的尝试:

import rpy2.robjects as robjects
from rpy2.robjects.packages import importr

robjects.r('install.packages("MatrixEQTL")')
mtrql = importr('MatrixEQTL')

我正在尝试访问类字段和类方法,但是我失败了,这是打印到python shell中时类的外观:

# to view class SlicedData of MatrixEQTL R package
print(mtrql.SlicedData)

Generator for class "SlicedData":

Class fields:
                                                           
Name:             dataEnv           nSlices1      rowNameSlices
Class:        environment            numeric               list
                                                           
Name:         columnNames      fileDelimiter    fileSkipColumns 
Class:          character          character            numeric
                                                           
Name:        fileSkipRows      fileSliceSize fileOmitCharacters
Class:            numeric            numeric          character

Class Methods: 
 "Clear","show#envRefClass","nSlices","getRefClass","export","initialize","CombineInOneSlice","callSuper","initFields","nCols","getClass","RowStandardizeCentered","import","SaveFile","RowReorder","setSlice","getSlice","RowReorderSimple","CreateFromMatrix","nRows","ResliceCombined","LoadFile","ColumnSubsample","SetNanRowMean","setSliceRaw","getSliceRaw","copy","RowMatrixMultiply","usingMethods","GetAllRowNames","RowRemoveZeroEps","field",".objectParent","IsCombined","untrace","trace","Clone","GetNRowsInSlice",".objectPackage","show","FindRow"

 Reference Superclasses: 
 "envRefClass"

我想访问实例类字段fileDelimiter,也要访问类方法字段LoadFile ,但是我不能,这也是我尝试访问类方法LoadFile和生成的错误消息的尝试:

# If I try to run this without "()"
data = mtrql.SlicedData

load_my_file = data.LoadFile(file)

    data = data.LoadFile(file)
 AttributeError: 'DocumentedSTFunction' object has no attribute 'LoadFile'

 # And that's my attempt for when adding "()" to the class name

 data = mtrql.SlicedData

 load_my_file = data.LoadFile(file)
    data = data.LoadFile(file)
 AttributeError: 'RS4' object has no attribute 'LoadFile'

我试图寻找解决此问题的方法,但未成功,请帮助我理解并解决此问题。

非常感谢您。

解决方法

mtrql.SlicedData是一个“生成器”,它是一个构造函数。在R中,这意味着一个函数(将返回该类的实例),这就是mtrql.SlicedData是具有rpy2的R函数的原因。

请参考R文档(https://rdrr.io/r/methods/Introduction.html)中的以下示例:

import rpy2.robjects as ro
Pos = ro.r("""
setClass("Pos",slots = c(latitude = "numeric",longitude = "numeric",altitude = "numeric"))
""")

对于rpy2,对象Pos是R函数:

>>> type(Pos)
rpy2.robjects.functions.SignatureTranslatedFunction

但是,该功能对象在R中具有S3类(R中有多个OOP系统,不幸的是其中两个在标准R中共存)。

>>> tuple(Pos.rclass)
('classGeneratorFunction',)

为此S3类实现了特定的print函数,它将为对象使用属性packageclassName(实际上是R函数-a-Generator)以显示有关您所看到的clas的所有信息。

由于这是构造函数,因此可以创建实例:

pos = Pos()

pos = Pos(latitude=0,longitude=0,altitude=-10)

实例将具有实例属性(和方法)

>>> tuple(pos.list_attrs())
('latitude','longitude','altitude','class')
>>> tuple(pos.do_slot('altitude'))
(-10,)

以您的特定示例为例,您可能想要以下内容:

slidata = mtrql.SlicedData()
slidata.do_slot('LoadFile')(file)

文档可以提供有关rpy2中的R S4类以及如何在Python中制作映射属性和方法的包装器类的更多信息。

https://rpy2.github.io/doc/v3.3.x/html/robjects_oop.html#s4-objects

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...