Search code examples
rcountspsssummary

Create summary table of categorical variables of different lengths


In SPSS it is fairly easy to create a summary table of categorical variables using "Custom Tables":

This example is from SPSS

How can I do this in R?

General and expandable solutions are preferred, and solutions using the Plyr and/or Reshape2 packages, because I am trying to learn those.

Example Data: (mtcars is in the R installation)

df <- colwise(function(x) as.factor(x) ) (mtcars[,8:11])

P.S.

Please note, my goal is to get everything in one table like in the picture. I have been strugling for many hours but my attempts have been so poor that posting the code probably won't add to the comprehensibility of the question.


Solution

  • One way to get the output, but not the formatting:

    library(plyr)
    ldply(mtcars[,8:11],function(x) t(rbind(names(table(x)),table(x),paste0(prop.table(table(x))*100,"%"))))
        .id 1  2       3
    1    vs 0 18  56.25%
    2    vs 1 14  43.75%
    3    am 0 19 59.375%
    4    am 1 13 40.625%
    5  gear 3 15 46.875%
    6  gear 4 12   37.5%
    7  gear 5  5 15.625%
    8  carb 1  7 21.875%
    9  carb 2 10  31.25%
    10 carb 3  3  9.375%
    11 carb 4 10  31.25%
    12 carb 6  1  3.125%
    13 carb 8  1  3.125%