Question

The book "Statistics and Computing", written by Venables and Ripley, has an example on defining a method function on objects of the class "polynomial" for the generic group function Math. Math is a group function with some component functions including abs, acos, acosh, ...

Below is the code mentioned in the book to define method function for the group generic function Math (note that the code is for S4 class (new-style R/S class)):

setMethod("Math", "polynomial", 
           function(x) {
            switch(.Generic, ceiling = , floor = , 
            trunc = polynomial(callGeneric(x@coef), rat = x@rat),
            stop(paste(.Generic, "not allowed on polynomials"))
            )}
         )

I understand that with setMethod() we are defining a method function for the generic function Math when it's called on an object of the class "polynomial". Would you explain what switch does here? I read the R help on switch but still have difficulty understanding the part below:

 switch(.Generic, ceiling = , floor = , 
            trunc = polynomial(callGeneric(x@coef), rat = x@rat),
            stop(paste(.Generic, "not allowed on polynomials"))
            )}

Note that the polynomial function above is a constructor function to create objects of the class "polynomial".

Was it helpful?

Solution

.Generic identifies the name used to call the current function. You can think of it like this: if the function was called as ceiling, floor or trunc, then the given implementation polynomial(callGeneric(x@coef), rat = x@rat) is called, otherwise an error is printed. An empty argument after an =, as seen for ceiling and floor, means a fall-through: the next argument which actually contains any code will be the one executed.

OTHER TIPS

I think it's informative to play with the code (this understanding I am about to disseminate is purely from what I just observed; I didn't even know you could use switch in this way):

Your code tweaked to run outside of the function:

test <- "ceiling"
test <- "floor"
test <- "trunc"

switch(test, 
    ceiling = , 
    floor = , 
    trunc = mean(1:10),
    stop(paste(test, "not allowed on polynomials"))
)

Try each of the conditions for test and you'll see that if ceiling, floor or trunc it returns what trunc =. If you put something in for floor:

test <- "floor"

switch(test, 
    ceiling = , 
    floor = 5, 
    trunc = mean(1:10),
    stop(paste(test, "not allowed on polynomials"))
)

You get a different response.

I may be wrong but I think this could have been written:

if (.Generic %in% c(ceiling, "floor", "trunc"){
    polynomial(callGeneric(x@coef), rat = x@rat)
} else {
    stop(paste(.Generic, "not allowed on polynomials"))
}

Interested if this interpretation is correct but am not familiar with this particular context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top