Ben Bolker
Ben Bolker

Reputation: 226172

methods for an object with length(class)>1

This question suggests using methods(class=class(obj)) to extract the list of methods that are available for an object.

If used on an object where length(class(obj))>1, this leads to lots of warnings, e.g.

set.seed(101)
a <- matrix(rnorm(20), nrow = 10)
b <- a + rnorm(length(a))
obj <- lm(b ~ a)

gives class(obj) as c("lm","mlm"); methods(class=class(obj)) gives

(many times)< Warning in grep(pattern, all.names, value = TRUE) : argument 'pattern' has length > 1 and only the first element will be used
Warning in gsub(name, "", S3reg) : argument 'pattern' has length > 1 and only the first element will be used
Warning in sub(paste0("\.", class, "$"), "", row.names(info)) : argument 'pattern' has length > 1 and only the first element will be used

followed by the results.

It seems (?) that applying methods(class=...) to the last element of class(obj) would work, but I'm interested in alternatives or discussion as to why that is (or is not) correct ...

To clarify, I would like the returned value to be a (preferably unique) character vector, so that I can use something like if ("foo" %in% allmethods(obj)) to test for the availability of a specified method for the object ...

Upvotes: 1

Views: 89

Answers (1)

Rui Barradas
Rui Barradas

Reputation: 76402

Is this what you're looking for?

sapply(class(obj), function(x) methods(class = x))

Note that the code below gives an error, since argument generic.function becomes mlm. It must be argument class like above.

sapply(class(obj), methods)
Error in .S3methods(generic.function, class, parent.frame()) : 
  no function 'mlm' is visible

Upvotes: 2

Related Questions