带有R Markdown的交叉制表

时间:2020-05-31 12:30:04

标签: r r-markdown markdown crosstab

我很难为 PDF编织的R Markdown 文档创建简单美观的交叉表。我有一个与此示例相似的数据集:

library(tidyverse)
fakeData <- tibble(id = c(1,2,3,4,5,6,7,8,9,10),
                   bmi = c("normal", "overweighted", "underweighted", "normal", "normal", "overweighted",
                           "normal", "overweighted", "underweighted","normal"),
                   gender = c("M", "F", "M", "M", "F", "F", "M", "F", "F", "F"))

我想得到这样的输出:

Desired output

有没有人有技巧/已知好的软件包来做到这一点?非常感谢!

2 个答案:

答案 0 :(得分:4)

我认为janitor软件包可以在这里为您提供帮助...

请注意:“总计”列中的百分比与您期望的输出不匹配...这是因为您在输出中混合了按百分比和按行百分比计算。这真的是您想要的吗?

library( janitor )

fakeTable <- fakeData %>% 
  tabyl( gender, bmi ) %>% 
  adorn_totals( where = c("row", "col") ) %>%
  adorn_percentages("row") %>%
  adorn_pct_formatting() %>%
  adorn_ns( position = "front" ) %>%
  adorn_title("combined")

# gender/bmi    normal overweighted underweighted       Total
#          F 2 (33.3%)    3 (50.0%)     1 (16.7%)  6 (100.0%)
#          M 3 (75.0%)    0  (0.0%)     1 (25.0%)  4 (100.0%)
#      Total 5 (50.0%)    3 (30.0%)     2 (20.0%) 10 (100.0%)

针织

library(knitr)
library(kableExtra)
fakeTable %>%
  kable() %>%
  kable_styling(bootstrap_options = c("condensed", "striped", "bordered")) 

enter image description here

答案 1 :(得分:1)

我认为软件包summarytools可以产生所需的输出。 使用您的fakeData:

library(summarytools)
print(ctable(x = fakeData$gender, y = fakeData$bmi, prop = "t"),
      method = "render")

enter image description here