以下行为的解释是什么?
is.list(data.frame()) ## TRUE
is(data.frame(),'list') ## FALSE
is(data.frame()) ## "data.frame" "list" "oldClass" "vector"
extends('data.frame','list') ## TRUE
inherits(data.frame(),'list') ## FALSE
以下行为的解释是什么?
is.list(data.frame()) ## TRUE
is(data.frame(),'list') ## FALSE
is(data.frame()) ## "data.frame" "list" "oldClass" "vector"
extends('data.frame','list') ## TRUE
inherits(data.frame(),'list') ## FALSE
您正在混合 S3 和 S4 类约定。is并且extends适用于 S4 类,但由于它们的实现方式,它们与 S3 类一起使用。inherits是为 S3 类编写的,它不适用于完全兼容的 S4 对象。
inherits有效地将结果class(x)与您在第二个参数中指定的类进行比较。因此
> class(data.frame())
[1] "data.frame"
不包含"list"任何地方,所以失败了。
另请注意?inherits:
The analogue of ‘inherits’ for formal classes is ‘is’. The two
functions behave consistently with one exception: S4 classes can
have conditional inheritance, with an explicit test. In this
case, ‘is’ will test the condition, but ‘inherits’ ignores all
conditional superclasses.
另一个混淆是对象的类和该对象的实现。是的,数据框是is.list()告诉我们的列表,但在 R 的 S3 类世界中,data.frame()它属于"data.frame"not类"list"。
至于is(data.frame(),'list'),那么它不是那个特定"list"的类,因此FALSE. 什么is(data.frame())记录在?is
Summary of Functions:
‘is’: With two arguments, tests whether ‘object’ can be treated as
from ‘class2’.
With one argument, returns all the super-classes of this
object's class
因此is(data.frame())显示"data.frame"类扩展的类(在 S4 意义上,而不是 S3 意义上)。这进一步解释了extends('data.frame','list')在 S4 世界中的行为,"data.frame"该类确实扩展了"list"该类。