Seeking a better understanding of S3 classes

Hi all,

I find OOP in general more difficult to understand than a functional approach. So lately I have been trying to improve my understanding of S3 classes.

I have never, so far as I can remember, seen either of the following patterns, but I would like to know if either of them are used / useful.


f <- function(x, y) {
  if (condition) class(x) <- 'newclass'
  UseMethod('f')
}

g <- function(x, y) {
  class(x) <- y
  UseMethod('g')
}

I provide a silly example of each below. They are not really objects, but hopefully they do enough to illustrate my questions. If they reveal obvious flaws in my thinking I'd welcome any insights.

Case 1

In this case the arguments supplied are all numeric, so a method can't be chosen based on the class unless a new class is assigned inthe generic.


rep2 <- function(x1, times1, x2, times2) {
  if (length(x1) > 1) class(x1) <- 'vec_2'
  cat('Class:', class(x1), '\n')
  UseMethod('rep2')
  # Or equivalently and more explicitly,
  #    since the class of x1 has just been assigned
  # UseMethod('rep2', x1)
}

rep2.default <- function(x1, times1, x2, times2) {
  list(rep(x1, times1), rep(x2, times2))
}

rep2.vec_2 <- function(x1, times1) {
  mapply(rep, x1, times1)
}

rep2(1, 2, 3, 4)
rep2(c(1, 2), c(3, 4))

Case 2

In this example, the method to be used depends on the object argument.
I think I get the intended usage of this, but would appreciate an explanation of when it is used to good effect? Any examples of use in the wild?

My motivation for this question, though, is what about the pattern used in the example below? Similar to the previous example, the class is set within the generic, but this time a second argument is passed to the object parameter of UseMethod.
Again, I am thinking of a situation when the object itself cannot be used to distinguish the method to be used.


spelling <- function(x, y = 'none') {
  class(x) <- y
  cat('Class:', class(x), '\n')
  UseMethod('spelling', x)
}

spelling.default <- function(x, y) {
  cat('I just like rainbows!!\n')
}

spelling.gb <- function(x, y) {
  cat(x, 'is my favourite colour\n')
}

spelling.us <- function(x, y) {
  cat(x, 'is my favorite color\n')
}

spelling('Grey')
spelling('Grey', 'gb')
spelling('Gray', 'us')

# rm(list = ls(patt = 'rep2|spelling'))

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.