[R] Particular Cross tables
Prof Brian D Ripley
ripley at stats.ox.ac.uk
Sun May 19 08:31:59 CEST 2002
On Sat, 18 May 2002, Kenneth Cabrera wrote:
> Dear R experts:
>
> I have this data base (data frame) with three variables
> where f1 and f2 are factors.
> I want to obtain a table with the sum of the third variable
> at each cross element of the two factors.
>
> Would you help me with any function idea?
>
> Original data base (data frame)
>
> f1 f2 v1
> 1 2 10
> 1 1 20
> 1 2 30
> 1 3 40
> 2 1 50
> 2 2 60
> 1 1 70
> 3 1 80
> 3 2 90
> 2 2 10
>
> I would like to obtain this matrix (sum of the crossed elements with
> zeros where I don't have any crossed factor)
>
> Factor 1
> 90 40 40
> Factor 2 50 70 0
> 80 90 0
> xtabs(v1~f1+f2, tab)
f2
f1 1 2 3
1 90 40 40
2 50 70 0
3 80 90 0
> attach(tab)
> (res <- tapply(v1, list(f1, f2), sum))
1 2 3
1 90 40 40
2 50 70 NA
3 80 90 NA
> res[is.na(res)] <- 0
> res
1 2 3
1 90 40 40
2 50 70 0
3 80 90 0
(You can add names to the dimnames by
> names(dimnames(res)) <- c("factor 1", "factor 2")
> res
factor 2
factor 1 1 2 3
1 90 40 40
2 50 70 0
3 80 90 0
)
> Is it possible to obtain any kind of function (not only sum())?
> (like sd(), for example?)
In the second form, yes, e.g.
(res <- tapply(v1, list(f1, f2), sd))
but cells with zero and one entries will both be NA, so you may want to use
the counts given by xbats(~f1+f2, tab) to distringuish them.
Brian
--
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