r - 是和继承有什么区别?

标签 r inheritance r-faq

如果我想检查变量是否继承自某个类,我可以使用 isinherits .

class(letters)
## [1] "character"
is(letters, "character")
## [1] TRUE
inherits(letters, "character")
## [1] TRUE

是否有我应该使用哪一个的偏好,它们是否会返回不同的值?

最佳答案

简短版本:

使用继承,但要小心数字和 S4 类。

<小时/>

更长的版本:

is 帮助页面的“另请参阅”部分:

inherits is nearly always equivalent to is, both for S4 and non-S4 objects, and is somewhat faster. The non-equivalence applies to classes that have conditional superclasses, with a non-trivial test= in the relation (not common and discouraged): for these, is tests for the relation but inherits by definition ignores conditional inheritance for S4 objects.

来自继承帮助页面的正式类部分:

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.

所以它们大多返回相同的东西,但是 inherits 更快,所以它应该是大多数情况下的默认选择。 (正如 Konrad 提到的,is 还要求加载 methods 包,这可能使其不适合 Rscript 的性能敏感用途。)

如果您使用具有条件继承的 S4 类,这些值可能会有所不同,但这是 not recommended (请参阅“方法选择和调度:详细信息”部分),这意味着这种情况很少见。

这两个函数最明显的不同之处是检查整数是否为数字时。

class(1L)
## [1] "integer"
is.numeric(1L)
## [1] TRUE
is(1L, "numeric")
## [1] TRUE
inherits(1L, "numeric")
## [1] FALSE

关于r - 是和继承有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27923345/

相关文章:

r - 如何在 data.table 中的多个列中使用 ifelse?

r - 从 R 中的 Excel 文件中提取超链接

java - 抽象类作为接口(interface)中的属性,将被子类覆盖

r - 为什么我不能得到小于 2.2e-16 的 p 值?

r - 将 UNIX 纪元转换为 Date 对象

r - 检查丢失的软件包并安装它们的优雅方法?

r - 如何在环境中使用名称?

r - 如何停止 read.table 在 R 中以不同精度舍入数字?

java - 是否可以将一个上下文注入(inject)到另一个上下文中?

c++ - 使用模板函数继承类