Jul 3, 2008

Simple tables with percentages

You can crosstabulate categorical data in R with table(), and get percentages with prop.table(). To get a combination of both, I programmed Table(), that provides this type of output:

> pets<-rep(c("cats","dogs"), 30)
> Table(pets)
pets (%)
cats 30 ( 50.0)
dogs 30 ( 50.0)

> size<-c("big","small")[sample(1:2,replace=TRUE, size=60 )] > Table(pets, size) # row percentages by default
size
pets big (%) small (%)
cats 13 ( 43.3) 17 ( 56.7)
dogs 19 ( 63.3) 11 ( 36.7)

> Table(pets, size, margin=2) # column percentages
size
pets big (%) small (%)
cats 13 ( 40.6) 17 ( 60.7)
dogs 19 ( 59.4) 11 ( 39.3)

> color<-c("black","brown","grey")[sample(1:3,replace=TRUE, size=60 )]
> Table(pets, size, color)

color = black
size
pets big (%) small (%)
cats 3 ( 33.3) 6 ( 66.7)
dogs 3 ( 75.0) 1 ( 25.0)

color = brown
size
pets big (%) small (%)
cats 6 ( 54.5) 5 ( 45.5)
dogs 6 ( 54.5) 5 ( 45.5)

color = grey
size
pets big (%) small (%)
cats 4 ( 40.0) 6 ( 60.0)
dogs 10 ( 66.7) 5 ( 33.3)

Only up to 3 dimensions, but these should be enough most of the cases.

You can download the code from here

I usually keep useful functions in an RData that I attach automatically in my Rprofile.

No comments: