jakub
jakub

Reputation: 5104

Is it possible to have "nested" methods for multiple classes in R?

Say a have two objects:

a = 1:3
class(a) = append("myclass", class(a))
class(a)
[1] "myclass" "integer"

b = c("a", "b", "c")
class(b) = append("myclass", class(b))
class(b)
[1] "myclass"   "character"

Is it then possible to define nested methods which would depend both on "myclass" and the basic/other custom class? E.g.

print.myclass.integer = function(x) { some code }
print.myclass.character = function(x) { different code }

If so, what is the correct procedure?

Upvotes: 2

Views: 195

Answers (2)

Tomás Barcellos
Tomás Barcellos

Reputation: 824

To have nested methods for multiples classes you just have to nest UseMethod():

print.myclass <- function(x) {
  UseMethod("print.myclass", x)
}

print.myclass.integer <- function(x) {
  print(paste("This method only prints the higher 'x': ", max(x)))
}

print.myclass.character <- function(x) {
  cat("This method scrambles the 'x' values:\n")
  print(sample(x, length(x)))
}

print(a) # [1] "This method only prints the hihger 'x':  3"
print(b) #This method scrambles the 'x' values:
         # [1] "a" "c" "b"

When you use print(), it will call UseMethod(), which will check for a myclass method. Then, it will call UseMethod() once more and it's now going to check for a method to the second class (integer or character) for the print.myclass function.

Take a look at ?UseMethod, methods(print) and The R Language Definition, p.28-31; it helped me out.

Upvotes: 0

nicola
nicola

Reputation: 24480

You can work around by checking inside print.myclass the other classes of the object. For instance:

print.myclass<-function(x,...) {
     if ("integer" %in% class(x)) print("some code") else 
        if ("character" %in% class(x)) print("some other code")
}
a
#[1] "some code"
b
#[1] "some other code"

Upvotes: 1

Related Questions