创建不同长度的分类变量的摘要表 [英] Create summary table of categorical variables of different lengths

查看:255
本文介绍了创建不同长度的分类变量的摘要表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SPSS中,使用自定义表格创建类别变量的汇总表非常容易:





我如何在R? / p>

一般和可扩展解决方案是首选,解决方案使用
Plyr和/或Reshape2软件包,因为我试图学习这些。



示例数据:(mtcars在R安装中)

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





请注意,我的目标是将所有内容都放入一个表格中,如图所示。
我已经挣扎了许多小时,但我的尝试是如此糟糕,发布代码可能不会增加的问题的可理解性。

解决方案

获取输出而不是格式化的一种方法:

  library(plyr)
ldply(mtcars [,8:11],function(x)t(rbind
.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档3 15 46.875%
6档4 12 37.5%
7档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%


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

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.

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆