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

标签 r r-s3

我想创建一个 S3 类。我如何确定哪种设置类属性的方法是正确的(因为它会产生影响)?

1) 覆盖类属性

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) 附加类属性

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

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):

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"

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

最佳答案

引用data.frame:

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

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

  • 追加 通常您不希望将您的类放在现有类之后。如果您这样做,那么只有在没有 data.frame 方法时才会调用它。

关于R S3 类 : Decide between overwriting vs appending the class name of the class attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45175988/

相关文章:

r - 为什么不使用 UseMethod 调度默认值?

r - 如何导出已排序的因子载荷表?

r - 查找组内行的变量值,该值是分组时另一个变量的最大值

r - 对 Ops 的通用方法进行分组(针对时间序列)

r - 分配 S3 子集运算符

r - 在 R 脚本中识别多余库()的快速方法?

r - 使用 plotly 和 Shiny 服务器复制图例条目

r - 使用Roxygen构建R包时的S3方法一致性警告

r - 多个类的 S3 运算符重载

r - 在 R6 类上实现 S3 调度的正确方法