Reputation: 47300
If I type methods(print)
I get a long list of methods.
For an object of class data.frame
, print.data.frame
will be called.
It's not always so simple though:
hw <- "hello world"
class(hw) # [1] "character"
There is no print.character
method. How do I know which method is called when executing print(hw)
?
Upvotes: 2
Views: 367
Reputation: 8836
Have you read Hadley's Advanced R and the chapter on objects? It might not give you the whole answer, but fundamentally what you're experiencing is the difference between method dispatch in C and regular S3 behaviour.
[
isn't really an R function, it's a C function and the decision of what method to use is done in C. That doesn't mean you can't create an S3 method for [
(or sum
, +
, [<-
and other .Primitive functions), but when you do it's more like you're making a wrapper/preprocess for the C function, which R will dispatch, before the ultimate decision is made by the C function based on classes defined separate from your regular (and extensible) R classes.
Or at least that's how I've understood it.
Upvotes: 1
Reputation: 269471
Turn debugging on for print and then run your example:
> debug(print)
> print("hello")
debugging in: print("hello")
debug: UseMethod("print")
Browse[2]> <---------------------------- press Enter to step forward
debugging in: print.default("hello") <-- this is the method that gets called
debug: {
noOpt <- missing(digits) && missing(quote) && missing(na.print) &&
missing(print.gap) && missing(right) && missing(max) &&
missing(useSource) && missing(...)
.Internal(print.default(x, digits, quote, na.print, print.gap,
right, max, useSource, noOpt))
}
Upvotes: 4