tags:

views:

100

answers:

3

I would like to know how to quickly find the specific function called by a generic function for a specific object. Example :

library(spatial)
data(redwood)
K <- Kest(redwood)
plot(K)

This is not an usual plot, it's a plot build for a Kest() object. So to investigate in order to find the function used, I do :

class(K)

I get

"fv" "data.frame"

I guess it is plot.fv

?plot.fv

Yey ! But I'm sure there a more efficient way than guessing. Anyone ?

+3  A: 

Hi Etiennebr,

You can find all of the corresponding generic functions for an S3 class using methods(). So in your case:

methods(class=fv)
eytan
@eytan: The function `methods` is actually in the `utils` package, not the methods package.
Richie Cotton
Marek's answer is really what I was looking for, but I like the simplicity and the elegance of your proposition, even if it require some manual digging.
Etiennebr
A: 

It is clear described in help to UseMethod.

When a function calling UseMethod("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, or an error results.

So if you looking for proper function you need to check all posibilities, eg.:

fun_seeker <- function(obj,fun) {
  funs_to_check <- paste(fun,c(class(obj),"default"),sep=".")
  funs_exists <- funs_to_check %in% methods(fun)
  if (any(funs_exists)) funs_to_check[funs_exists][1] else stop("No applicable method")
}
fun_seeker(matrix(rnorm(100),10),"plot")
fun_seeker(matrix(rnorm(100),10),"summary")
Marek
A: 

In this case we are dealing with an S3 class. (This is the older, simpler object oriented style.) This means that when you type plot(K) for an object with class "fv" "data.frame", R does the following:

It looks through the search path to find a function named plot. Type search() to see where R looks. Assuming you haven't done something silly like defining your own plot function, it should find the version in the graphics package.

This function has some special logic for dealing with an input where x is a function, then calls UseMethod.

UseMethod looks on the serach path for a function named plot.fv, and calls it if it finds it.

Failing that, it looks for plot.data.frame.

Failing that, it looks for plot.default.

If that couldn't be found an error would have been thrown. (Though plot.default exists in the graphics package, so you'd have to try quite hard to get an error here.)

Richie Cotton