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

Viewed 646

I want to create an S3 class. How do I decide which way of setting the class attribute is the right one (since it makes a difference)?

1) Overwrite the class attribute

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) Append the class attribute

I could also append the class name (at the beginning or end):

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"

I know that appending the class name at the beginning vs. at the end potentially changes the function that is called (from ?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. if I define an overloaded function it is not always called:

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

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

print(object2)
#   field1 field2
# 1      a      2

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

So my question is: How do I decide how to set the class name (which [other] criteria I have to consider)?

1 Answers
Related