Create summary table of categorical variables of different lengths

后端 未结 6 651
伪装坚强ぢ
伪装坚强ぢ 2021-01-02 11:04

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

\"This

6条回答
  •  青春惊慌失措
    2021-01-02 11:46

    A base R solution using lapply() and do.call() with rbind() to stitch together the pieces:

    x <- lapply(mtcars[, c("vs", "am", "gear", "carb")], table)
    
    neat.table <- function(x, name){
      xx <- data.frame(x)
      names(xx) <- c("Value", "Count")
      xx$Fraction <- with(xx, Count/sum(Count))
      data.frame(Variable = name, xx)
    }
    
    do.call(rbind, lapply(seq_along(x), function(i)neat.table(x[i], names(x[i]))))
    

    Results in:

       Variable Value Count Fraction
    1        vs     0    18  0.56250
    2        vs     1    14  0.43750
    3        am     0    19  0.59375
    4        am     1    13  0.40625
    5      gear     3    15  0.46875
    6      gear     4    12  0.37500
    7      gear     5     5  0.15625
    8      carb     1     7  0.21875
    9      carb     2    10  0.31250
    10     carb     3     3  0.09375
    11     carb     4    10  0.31250
    12     carb     6     1  0.03125
    13     carb     8     1  0.03125
    

    The rest is formatting.

提交回复
热议问题