[R] xtabs
Prof Brian D Ripley
ripley at stats.ox.ac.uk
Thu Feb 14 09:11:53 CET 2002
On Wed, 13 Feb 2002, Michael Lynn Fugate wrote:
> Hi,
>
> In Splus if I call the function crosstabs() the output is a contigency
> table; in each cell of the table is printed: N, N/RowTotal,
> N/ColTotal, N/Total. N is the number of observations in each cell.
Actually, that's not the output of crosstabs. That's how print.crosstabs
prints it. It seems a blunderbiss from the SAS/SPSS days of giving you all
the output you are deeemd ever to want, although it is unlikely that you
want more than one or at most two of the pieces of information.
> The same call to xtabs() in R will produce the contigency table but the
> only entry in each cell is N.
>
> How can I get the same relative frequencies that crosstabs() gives?
Here's an example
data(warpbreaks)
tab <- xtabs(breaks ~ wool + tension, data = warpbreaks)
> tab
tension
wool L M H
A 401 216 221
B 254 259 169
> tab/sum(tab)
tension
wool L M H
A 0.2638158 0.1421053 0.1453947
B 0.1671053 0.1703947 0.1111842
> tab/apply(tab, 1, sum) # N/RowTotal
tension
wool L M H
A 0.4785203 0.2577566 0.2637232
B 0.3724340 0.3797654 0.2478006
# both N/ColTotal
> sweep(tab, 2, apply(tab, 2, sum), "/")
> tab/(rep(1, 2) %o% apply(tab, 2, sum))
tension
wool L M H
A 0.6122137 0.4547368 0.5666667
B 0.3877863 0.5452632 0.4333333
--
Brian D. Ripley, ripley at stats.ox.ac.uk
Professor of Applied Statistics, http://www.stats.ox.ac.uk/~ripley/
University of Oxford, Tel: +44 1865 272861 (self)
1 South Parks Road, +44 1865 272860 (secr)
Oxford OX1 3TG, UK Fax: +44 1865 272595
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !) To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
More information about the R-help
mailing list