The Art of R Programming

(WallPaper) #1
Let’s try creating an instance of this object and then printing it:


x <- c(1,2,3)
y <- c(1,3,8)
lmout <- lm(y ~ x)
class(lmout)
[1] "lm"
lmout



Call:
lm(formula=y~x)


Coefficients:
(Intercept) x
-3.0 3.5


Here, we printed out the objectlmout. (Remember that by simply typ-
ing the name of an object in interactive mode, the object is printed.) The
R interpreter then saw thatlmoutwas an object of class"lm"and thus called
print.lm(), a special print method for the"lm"class. In R terminology, the
call to the generic functionprint()was dispatched to the methodprint.lm()
associated with the class"lm".
Let’s take a look at the generic function and the class method in
this case:



print
function(x, ...) UseMethod("print")



print.lm
function (x, digits = max(3, getOption("digits") - 3), ...)
{
cat("\nCall:\n", deparse(x$call), "\n\n", sep = "")
if (length(coef(x))) {
cat("Coefficients:\n")
print.default(format(coef(x), digits = digits), print.gap = 2,
quote = FALSE)
}
else cat("No coefficients\n")
cat("\n")
invisible(x)
}


You may be surprised to see thatprint()consists solely of a call to
UseMethod(). But this is actually the dispatcher function, so in view ofprint()’s
role as a generic function, you should not be surprised after all.


Object-Oriented Programming 209
Free download pdf