2017-04-14 71 views
1

我拥有包含多个人口因素的数据。将多个汇总表与子标题结合使用

我想创建这样的出版质量的汇总表:

     N 
Sex 
     M    150 
     F    150 
Marital Status 
     Single  100 
     Married  100 
     Divorced  100 
Age 
     <25   75 
     25-34   75 
     35-44   75 
     >= 45   75 

我可以很容易地产生这样每个人一块,就像这样:

require(dplyr) 

dd <- data.frame(barcode = c("16929", "64605", "03086", "29356", "23871"), 
    sex = factor(c("M", "F", "M", "F", "M")), 
    marital = factor(c("Married", "Single", "Single", "Single", "Divorced")), 
    age_group = factor(c("<25", "25-34", "35-44", "45-54", ">= 55"))) 

require(dplyr) 

age_groups <- dd %>% group_by(age_group) %>% count() 
sex <- dd %>% group_by(sex) %>% count() 
marital <- dd %>% group_by(marital) %>% count() 

,我能创造个人使用几种解决方案中的任何一种来为他们中的每个解决方案表,如kablepander

require(knitr) 
kable(age_groups) 
kable(sex) 
kable(marital) 

但我不能找到一种方法,他们为每个类别副标题组合成一个单一的表的部分。单独的表格有不同的列宽,并用手对齐它们并插入插入的子标题行(在未加工的LaTeX中?)似乎是一个不好的解决方案。

这是一个非常常见的报告格式 - 许多期刊文章的标准表1 - 我想找到一个通用的解决方案来创建它。

+0

我通常的解决办法是把这些值与行和列名安装一个矩阵就是我想要在表格和NA值我想要的空间。然后,我使用相同名称的包中的'xtable'构造一个Latex表。有关于如何让它跨越多行的SO帖子,但它可以是一个棘手的工作。 – lmo

回答

2
library(expss) 
library(knitr) 
dd = data.frame(barcode = c("16929", "64605", "03086", "29356", "23871"), 
       sex = factor(c("M", "F", "M", "F", "M")), 
       marital = factor(c("Married", "Single", "Single", "Single", "Divorced")), 
       age_group = factor(c("<25", "25-34", "35-44", "45-54", ">= 55"), 
            levels = c("<25", "25-34", "35-44", "45-54", ">= 55"))) 


dd %>% tab_cells("Sex" = sex, "Marital status" = marital, "Age" = age_group) %>% 
    tab_cols(total(label = "N")) %>% 
    tab_stat_cases(total_row_position = "none") %>% 
    tab_pivot() 

以上代码生成的输出如在你的榜样,但仅适用于HTML输出工作。 第二个代码片段适用于所有knitr格式,但输出与您的示例略有不同。

dd %>% tab_cells("Sex" = sex, "Marital status" = marital, "Age" = age_group) %>% 
    tab_cols(total(label = "N")) %>% 
    tab_stat_cases(total_row_position = "none") %>% 
    tab_pivot() %>% 
    split_columns() %>% 
    kable() 

首页输出:

第二输出:

0

这不是一个完整的解决方案,但一个好的开始可能是pander包。

library(pander) 
pander(list(`Age groups` = age_groups, `Sex` = sex, `Marital` = marital)) 
# 
# 
# * **Age groups**: 
# 
#  --------------- 
#  age_group n 
#  ----------- --- 
#   <25  1 
# 
#  >= 55  1 
# 
#  25-34  1 
# 
#  35-44  1 
# 
#  45-54  1 
#  --------------- 
# 
# * **Sex**: 
# 
#  --------- 
#  sex n 
#  ----- --- 
#  F 2 
# 
#  M 3 
#  --------- 
# 
# * **Marital**: 
# 
#  -------------- 
#  marital n 
#  ---------- --- 
#  Divorced 1 
# 
#  Married 1 
# 
#  Single 3 
#  -------------- 
# 
# 
# <!-- end of list --> 
# 
# 
相关问题