创建不同长度的分类变量汇总表 [英] Create summary table of categorical variables of different lengths
问题描述
在 SPSS 中,使用自定义表"创建分类变量汇总表相当容易:
In SPSS it is fairly easy to create a summary table of categorical variables using "Custom Tables":
如何在 R 中执行此操作?
首选通用和可扩展的解决方案,使用Plyr 和/或 Reshape2 包,因为我正在尝试学习这些.
General and expandable solutions are preferred, and solutions using the Plyr and/or Reshape2 packages, because I am trying to learn those.
示例数据:(mtcars 在 R 安装中)
Example Data: (mtcars is in the R installation)
df <- colwise(function(x) as.factor(x) ) (mtcars[,8:11])
附言
请注意,我的目标是将所有内容都放在一个表中,如图所示.我已经挣扎了好几个小时,但我的尝试非常糟糕,以至于发布代码可能不会增加问题的可理解性.
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.
推荐答案
获得输出的一种方法,但不是格式:
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%
这篇关于创建不同长度的分类变量汇总表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!