gpt4 book ai didi

r - 在 R 中, `is.list(x)` 和 `is(x,' 列表之间的不同行为')`

转载 作者:行者123 更新时间:2023-12-01 18:01:09 24 4
gpt4 key购买 nike

以下行为的解释是什么?

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 类约定。 isextends 适用于 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" 而不是 "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" 类。

关于r - 在 R 中, `is.list(x)` 和 `is(x,' 列表之间的不同行为')`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17798203/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com