The Art of R Programming

(WallPaper) #1
So, the function is in theutilsnamespace, and we can execute it by
adding such a qualifier:

> utils:::print.aspell(aspout)
mispelled
wrds:1:15

You can see all the generic methods this way:

> methods(class="default")

9.1.4 Writing S3 Classes.............................................


S3 classes have a rather cobbled-together structure. A class instance is cre-
ated by forming a list, with the components of the list being the member
variables of the class. (Readers who know Perl may recognize this ad hoc
nature in Perl’s own OOP system.) The"class"attribute is set by hand by
using theattr()orclass()function, and then various implementations of
generic functions are defined. We can see this in the case oflm()by inspect-
ing the function:

>lm
...
z <- list(coefficients = if (is.matrix(y))
matrix(,0,3) else numeric(0L), residuals = y,
fitted.values = 0*y, weights = w, rank = 0L,
df.residual = if (is.matrix(y)) nrow(y) else length(y))
}
...
class(z) <- c(if(is.matrix(y)) "mlm", "lm")
...

Again, don’t mind the details; the basic process is there. A list was cre-
ated and assigned toz, which will serve as the framework for the"lm"class
instance (and which will eventually be the value returned by the function).
Some components of that list, such asresiduals, were already assigned when
the list was created. In addition, the class attribute was set to"lm"(and possi-
bly to"mlm", as will be explained in the next section).
As an example of how to write an S3 class, let’s switch to something
simpler. Continuing our employee example from Section 4.1, we could
write this:

> j <- list(name="Joe", salary=55000, union=T)
> class(j) <- "employee"
> attributes(j) # let's check

212 Chapter 9

Free download pdf