Suppose we wish to present this data at a meeting, concentrating on
those respondents who know they will vote for X in the current election. In
other words, we wish to eliminate the Not Sure entries and present a sub-
table that looks like this:
Voted.for.X.Last.Time
Vote.for.X No Yes
No 2 0
Yes 1 1
The functionsubtable()below performs subtable extraction. It has two
arguments:
- tbl: The table of interest, of class"table".
- subnames: A list specifying the desired subtable extraction. Each compo-
nent of this list is named after some dimension oftbl, and the value of
that component is a vector of the names of the desired levels.
So, let’s review what we have in this example before looking at the code.
The argumentcttabwill be a two-dimensional table, with dimension names
Voted.for.XandVoted.for.X.Last.Time. Within those two dimensions, the level
names areNo,Not Sure, andYesin the first dimension, andNoandYesin the
second. Of those, we wish to exclude theNot Surecases, so our actual argu-
ment corresponding to the formal argumentsubnamesis as follows:
list(Vote.for.X=c("No","Yes"),Voted.for.X.Last.Time=c("No","Yes"))
We can now call the function.
> subtable(cttab,list(Vote.for.X=c("No","Yes"),
+ Voted.for.X.Last.Time=c("No","Yes")))
Voted.for.X.Last.Time
Vote.for.X No Yes
No20
Yes 1 1
Now that we have a feel for what the function does, let’s take a look at its
innards.
1 subtable <- function(tbl,subnames) {
2 # get array of cell counts in tbl
3 tblarray <- unclass(tbl)
4 # we'll get the subarray of cell counts corresponding to subnames by
5 # calling do.call() on the "[" function; we need to build up a list
6 # of arguments first
7 dcargs <- list(tblarray)
8 ndims <- length(subnames) # number of dimensions
132 Chapter 6