R中是否有一个函数可以告诉我给定对象(或类)的属性?
传递file类时,请考虑python中的"dir"函数:
>>> dir(file)
['__class__', '__delattr__', '__doc__', '__enter__', '__exit__',
'__format__', '__getattribute__', '__hash__', '__init__', '__iter__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'close', 'closed',
'encoding', 'errors', 'fileno', 'flush', 'isatty', 'mode', 'name',
'newlines', 'next', 'read', 'readinto', 'readline', 'readlines',
'seek', 'soft space', 'tell', 'truncate', 'write', 'writelines',
'xreadlines']
Run Code Online (Sandbox Code Playgroud)
也许还有一个相同的type(?)
>>> type(1)
<type 'int'>
Run Code Online (Sandbox Code Playgroud)
R为您提供了几种不同的面向对象系统,因此如果您不知道要处理的对象类型,首先需要确定它是S3,S4还是RC中的一种.使用isS4(x)和is(x, 'refClass')为此.如果它不是S4而不是RC,那就是S3.有关更多信息,请参阅Hadley关于面向对象编程的高级R章节.
对于S3和S4对象,需要调用几个函数来获取与Python相当的信息dir.所有这些方法都要求您提供对象类的名称作为参数,您可以使用该class函数来确定.
对于方法,methods(class=class(x))用于S3对象和showMethods(class=class(x))S4对象.要显示"属性"名称/值,请使用attributes(x)S3对象和getSlots(class(x))S4对象.注意,getSlots只会显示插槽名称和类型,而不是它们的值.要访问这些值,您必须使用slot,但只需在将对象打印到控制台时打印这些值.