The Art of R Programming

(WallPaper) #1

Let’s go through an example. R includes facilities for constructingcon-
tingency tables, which we discussed in Section 6.4. An example in that section
involved an election survey in which five respondents are asked whether they
intend to vote for candidate X and whether they voted for X in the last elec-
tion. Here is the resulting table:



cttab <- table(ct)
cttab
Voted.for.X.Last.Time
Vote.for.X No Yes
No 2 0
Not Sure 0 1
Yes 1 1



For instance, two respondents answered no to both questions.
The objectcttabwas returned by the functiontableand thus is likely of
class"table". A check of the documentation (?table) confirms this. But what
is in the class?
Let’s explore the structure of that objectcttabof class"table".



ctu <- unclass(cttab)
ctu
Votes.for.X.Last.Time
Vote.for.X No Yes
No 2 0
Not Sure 0 1
Yes 1 1
class(ctu)
[1] "matrix"



So, the counts portion of the object is a matrix. (If the data had involved
three or more questions, rather than just two, this would have been a higher-
dimensional array.) Note that the names of the dimensions and of the indi-
vidual rows and columns are there, too; they are associated with the matrix.
Theunclass()function is quite useful as a first step. If you simply print
an object, you are at the mercy of the version ofprint()associated with
that class, which may in the name of succinctness hide or distort some valu-
able information. Printing the result of callingunclass()allows you to work
around this problem, though there was no difference in this example. (You
saw an instance in which it did make a difference in the section about S3
generic functions in Section 9.1.1 earlier.) The functionstr()serves the
same purpose, in a more compact manner.
Note, though, applyingunclass()to an object still results in an object
with some basic class. Here,cttabhad the class"table", butunclass(cttab)
still had the class"matrix".
Let’s try looking at the code fortable(), the library function that pro-
ducedcttab. We could simply typetable, but since this is a somewhat longish


Object-Oriented Programming 229
Free download pdf