The Art of R Programming

(WallPaper) #1
This makes it easy to call a function with a variable number of
arguments.
For our example, we need to form a list consisting first oftblarrayand
then the user’s desired levels for each dimension. Our list looks like this:

list(tblarray,Vote.for.X=c("No","Yes"),Voted.for.X.Last.Time=c("No","Yes"))

Lines 7 through 11 build up this list for the general case. That’s our sub-
array. Then we need to attach the names and set the class to"table". The
former operation can be done via R’sarray()function, which has the follow-
ing arguments:


  • data: The data to be placed into the new array. In our case, this issubarray.

  • dim: The dimension lengths (number of rows, number of columns, num-
    ber of layers, and so on). In our case, this is the valuendims, computed in
    line 16.

  • dimnames: The dimension names and the names of their levels, already
    given to us by the user as the argumentsubnames.


This was a somewhat conceptually complex function to write, but it gets
easier once you’ve mastered the inner structures of the"table"class.

6.3.3 Extended Example: Finding the Largest Cells in a Table.............


It can be difficult to view a table that is very big, with a large number of rows
or dimensions. One approach might be to focus on the cells with the largest
frequencies. That’s the purpose of thetabdom()function developed below—
it reports the dominant frequencies in a table. Here’s a simple call:

tabdom(tbl,k)

This reports the cells in the tabletblthat have theklargest frequencies.
Here’s an example:

> d <- c(5,12,13,4,3,28,12,12,9,5,5,13,5,4,12)
> dtab <- table(d)
> tabdom(dtab,3)
d Freq
35 4
512 4
24 2

The function tells us that the values 5 and 12 were the most frequent in
d, with four instances each, and the next most frequent value was 4, with two
instances. (The 3, 5, and 2 on the left are actually extraneous information;
see the following discussion regarding converting a table to a data frame.)

134 Chapter 6

Free download pdf