Re: [S]: Arguments to table()

Bill Venables (wvenable@attunga.stats.adelaide.edu.au)
Fri, 26 Jun 1998 09:55:58 +0930


Ross Darnell writes:
> I am trying to construct a contingency table of factor levels defined
> as (say 3) columns of a dataframe, X.
>
> table(X) gives a one dimensional table.
>
> apply(X,2,table) gives 3 marginal tables.
>
> table(X$V1,X$V2,X$V3) gives the correct answer but isn't a useful
> method for a general dataframe.
>
> There is obviously a simple solution, but not so obvious to me.

Indeed there are at least two simple solutions.

Suppose `datfr' is a data frame with an arbitrary number, n, of
factor components and I need to find the n-way contingency table
they define. Refugees from SPSS will rejoice in the solution

tab <- crosstabs(~ . , datfr)

but the result carries a lot of extra baggage. If you want just
the bare table with dimnames you will probably want to do:

tab <- structure(crosstabs(~ . , datfr),
marginals = NULL, call = NULL, class = NULL)

The general problem, though, is "How do I call a function with an
arbitrary number of arguments?" and for this there is a general
solution. The following will do it:

tab <- do.call("table", datfr)

It is often a defining moment in many S programmers' lives when
they finally see the need for do.table.

Bill Venables.
-----------------------------------------------------------------------
This message was distributed by s-news@wubios.wustl.edu. To unsubscribe
send e-mail to s-news-request@wubios.wustl.edu with the BODY of the
message: unsubscribe s-news