[R] crosstabulation of means
Frank E Harrell Jr
fharrell at virginia.edu
Thu May 23 21:21:08 CEST 2002
On Thu, 23 May 2002 13:56:52 -0400
"R. Heberto Ghezzo" <heberto.ghezzo at mcgill.ca> wrote:
> Hello, I am trying to print a crosttabulation of mean,sd,n for a
> continuous variable crossclassified by anoother/s grouping variables. I
> came up with:
> xtab2 <- function(x,g1,g2) {
> funy <- function(z)
> list(mean(z,na.rm=T),sd(z,na.rm=T),length(z))
> aa <- by(x,list(g1,g2),funy)
> bb <- matrix(unlist(aa),nrow=3
> ,dimnames=list(c("mean","sd","n"),
> rep(levels(as.factor(g2)),
> rep(length(levels(as.factor(g1))),
> length(levels(as.factor(g2)))) ) ))
> }
> but as you can see the labels of the columns correspond only to the
> second factor, and if I try to generalize it to 3 grouping variables the
> thing does not work.
> Any suggestions please on how to write the dimnames paragraph
> appropriately?
> Thanks
>
There are many ways to do this. One is to use functions in the Hmisc library:
s <- summarize(x, llist(g1,g2,g3,g4), smean.sd) # smean.sd is in Hmisc: mean,sd
To make a nice table (but only up to 2 cross-classification variables) do:
summary(x ~ g1+g2, method='cross', fun=smean.sd)
The latter will include the Ns for each cell.
Frank Harrell
>
> -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
> 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
> _._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._
--
Frank E Harrell Jr Prof. of Biostatistics & Statistics
Div. of Biostatistics & Epidem. Dept. of Health Evaluation Sciences
U. Virginia School of Medicine http://hesweb1.med.virginia.edu/biostat
-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
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