soeren.vogel at eawag.ch
2009-Mar-08 17:14 UTC
[R] Summary of data.frame according to colnames and grouping factor
A dataframe holds 3 vars, each checked true or false (1, 0). Another var holds the grouping, r and s: ### start:example set.seed(20) d <- data.frame(sample(c(0, 1), 20, replace=T), sample(c(0, 1), 20, replace=T), sample(c(0, 1), 20, replace=T)) names(d) <- c("A", "B", "C") e <- rep(c("r", "s"), 10) ### end:example How do I get the count of "1's" (or any other function) applied over each var according to the grouping? That is: Desired output table: A B C r count count count s ... ... ... or likewise transposed. I'd like to use the table for textual display and/or barplot creation. Thx, S?ren -- S?ren Vogel, PhD-Student, Eawag, Dept. SIAM http://www.eawag.ch, http://sozmod.eawag.ch
baptiste auguie
2009-Mar-08 17:23 UTC
[R] Summary of data.frame according to colnames and grouping factor
Hi, You could use the reshape package:> d$e <- e > > recast(d, variable~e, fun=sum)The doBy package is another option. baptiste On 8 Mar 2009, at 17:14, soeren.vogel at eawag.ch wrote:> A dataframe holds 3 vars, each checked true or false (1, 0). Another > var holds the grouping, r and s: > > ### start:example > set.seed(20) > d <- data.frame(sample(c(0, 1), 20, replace=T), sample(c(0, 1), 20, > replace=T), sample(c(0, 1), 20, replace=T)) > names(d) <- c("A", "B", "C") > e <- rep(c("r", "s"), 10) > ### end:example > > How do I get the count of "1's" (or any other function) applied over > each var according to the grouping? That is: > > Desired output table: > > A B C > r count count count > s ... ... ... > > or likewise transposed. I'd like to use the table for textual display > and/or barplot creation. > > Thx, S?ren > > -- > S?ren Vogel, PhD-Student, Eawag, Dept. SIAM > http://www.eawag.ch, http://sozmod.eawag.ch > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code._____________________________ Baptiste Augui? School of Physics University of Exeter Stocker Road, Exeter, Devon, EX4 4QL, UK Phone: +44 1392 264187 http://newton.ex.ac.uk/research/emag