Create summary table of categorical variables of different lengths

后端 未结 6 652
伪装坚强ぢ
伪装坚强ぢ 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:32

    Here's my solution. It ain't pretty, which is why I put a bag over its head (wrap it in a function). I also add another variable to demonstrate that it's general (I hope).

    prettyTable <- function(x) {
    
      tbl <- apply(x, 2, function(m) {
        marc <- sort(unique(m))
        cnt <- matrix(table(m), ncol = 1)
        out <- cbind(marc, cnt)
        out <- out[order(marc), ] # do sorting
        out <- cbind(out, round(prop.table(out, 2)[, 2] * 100, 2))
      })
    
      x2 <- do.call("rbind", tbl)
    
      spaces <- unlist(lapply(apply(x, 2, unique), length))
      space.names <- names(spaces)
      spc <- rep("", sum(spaces))
      ind <- cumsum(spaces)
      ind <- abs(spaces - ind)+1
      spc[ind] <- space.names
    
      out <- cbind(spc, x2)
      out <- as.data.frame(out)
    
      names(out) <- c("Variable", "Levels", "Count", "Column N %")
      out
    }
    
    prettyTable(x = mtcars[, c(2, 8:11)])
    
       Variable Levels Count Column N %
    1       cyl      4    11      34.38
    2                6     7      21.88
    3                8    14      43.75
    4        vs      0    18      56.25
    5                1    14      43.75
    6        am      0    19      59.38
    7                1    13      40.62
    8      gear      3    15      46.88
    9                4    12       37.5
    10               5     5      15.62
    11     carb      1     7      21.88
    12               2    10      31.25
    13               3     3       9.38
    14               4    10      31.25
    15               6     1       3.12
    16               8     1       3.12
    

    Using googleVis package, you can make a handy html table.

    plot(gvisTable(prettyTable(x = mtcars[, c(2, 8:11)])))
    

    enter image description here

提交回复
热议问题