R S3 class:决定是覆盖还是附加 class 属性的 class 名称

R S3 class: Decide between overwriting vs appending the class name of the class attribute

我想创建一个 S3 class。我如何确定哪种设置 class 属性的方式是正确的(因为它有所不同)?

1) 覆盖class属性

object <- data.frame(field1 = "a", field2 = 2)
class(object)
# [1] "data.frame"
class(object) <- "MyClass"    # set the class by overwriting the existing one
class(object)
# [1] "MyClass"

2) 追加 class 属性

我还可以附加 class 名称(在开头或结尾):

object2 <- data.frame(field1 = "a", field2 = 2)
class(object2) <- append(class(object2), "MyClass")
class(object2)
# [1] "data.frame"    "MyClass"

object3 <- data.frame(field1 = "a", field2 = 2)
class(object3) <- append("MyClass", class(object3))
class(object3)
# [1] "MyClass"    "data.frame"

我知道在开头和末尾附加 class 名称可能会改变调用的函数(来自 ?class):

When a generic function fun is applied to an object with class attribute c("first", "second"), the system searches for a function called fun.first and, if it finds it, applies it to the object. If no such function is found, a function called fun.second is tried. If no class name produces a suitable function, the function fun.default is used (if it exists).

E. G。如果我定义一个重载函数,它并不总是被调用:

print.MyClass <- function(x) { print("printing MyClass") }

print(object)
# [1] "printing MyClass"

print(object2)
#   field1 field2
# 1      a      2

print(object3)
# [1] "printing MyClass"

所以我的问题是:我如何决定如何设置 class 名称(我必须考虑哪些 [other] 标准)?

参考data.frame:

  • 覆盖 如果您将 class 名称替换为您自己的名称,那么您必须为每个可以调用的泛型定义您自己的方法它除非那个泛型的默认方法是好的。如果您的 class 与数据框完全不同,那么这就是您想要的。例如,如果无法在您的对象上使用 data.frame 方法。

  • Prepending 如果您将 class 名称添加到 class 向量之前,那么当使用具有您的对象调用泛型时new class name 那么泛型将首先查看您是否为它定义了一个方法,如果没有,它将调用 data.frame 方法。如果您想覆盖数据框的某些功能但使用其他功能,这就是您想要的。例如,在 tibble 包中,tibble 对象的 class 向量是 c("tbl_df", "tbl", "data.frame"),而在 data.table 包中,data.table 对象的 class 向量是c("data.table", "data.frame")

  • Appending 通常您不想将 class 放在现有的 class 之后。如果你这样做了,那么它只会在没有 data.frame 方法的情况下被调用。