[R] Summarizing counts by multiple factors

William Dunlap wdunlap at tibco.com
Wed May 12 18:20:10 CEST 2010


> From: r-help-bounces at r-project.org 
> [mailto:r-help-bounces at r-project.org] On Behalf Of Noah Silverman
> Sent: Tuesday, May 11, 2010 5:38 PM
> To: r-help at r-project.org
> Subject: [R] Summarizing counts by multiple factors
> 
> Hi,
> 
> An example data set is:
> 
> group    level    color
> A        1        "blue"
> A        1        "Red"
> B        1        "blue"
> B        2        "Red"
> A        2        "Red"
> B        2        "Red"
> B        2        "blue"
> B        2        "blue"
> A        2        "blue"
> A        2        "Red"
> 
> 
> I'd like to compute a summary of counts for each combination 
> of group, 
> level, color.
> 
> An example output would be something like this:
> group    level    color        count
> A        1        "blue"        1
> A        2        "red"        2
> B        2        "red"        2
> etc..
> 
> 
> The tapply function seems to do this for a single variable, but I can 
> figure out to to do it for combinations of more than one 
> factor.

The by= argument can be a list of several factors.
You can also give it the output of interaction(fac1,fac2).

For nice printing you might also like the ftable function.
With your dataset stored in the data.frame called "d" I get:

  > ft <- ftable(1~group+level+color, data=d)
  > ft
  group level color   
  A     1     blue   1
              Red    1
        2     blue   1
              Red    2
  B     1     blue   1
              Red    0
        2     blue   2
              Red    2
  > dft <- as.data.frame(ft)
  > dft[dft$Freq>0,,drop=FALSE]
    group level color Freq
  1     A     1  blue    1
  2     B     1  blue    1
  3     A     2  blue    1
  4     B     2  blue    2
  5     A     1   Red    1
  7     A     2   Red    2
  8     B     2   Red    2

Rearranging the terms in the formula given to ftable()
will rearrange the table:
  > ftable(color~group+level, data=d)
              color blue Red
  group level               
  A     1              1   1
        2              1   2
  B     1              1   0
        2              2   2
  > ftable(color+level~group, data=d)
        color blue   Red  
        level    1 2   1 2
  group                   
  A              1 1   1 2
  B              1 2   0 2

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com 

> I also 
> see the ave function, but can't figure out how to apply it to 
> multiple 
> factors.
> 
> Any suggestions?
> 
> Thanks
> 
> ______________________________________________
> 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.
> 



More information about the R-help mailing list