如果我想检查变量是否继承自某个类,我可以使用 is
或inherits
.
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/