使用 kable 在 R markdown 中格式化数据以创建整洁的 table

Format data to create neat table in R markdown using kable

我想使用 kable 包在 R markdown 中创建一个整洁的 table,但我的数据需要转换。

我的数据是这样的:

category <- c('population', 'population', 'sample', 'sample', 'population', 'population', 'sample', 'sample')
gender <- c('female', 'male', 'female', 'male', 'female', 'male', 'female', 'male')
n <- c(12,20,14,14,11,21,13,15)
frequency <- c(0.375, 0.625, 0.5, 0.5, 0.34375, 0.65625, 0.4642857, 0.5357143)
cohort <- c('one', 'one', 'one', 'one', 'two', 'two', 'two', 'two')

df <- data.frame(category, gender, n, frequency, cohort)

我想在 R markdown 中创建一个如下所示的 table(但我欢迎其他建议):

关于如何解决这个问题有什么想法吗?感谢您的帮助!

正如@rjen 所建议的,kableExtra 包可能适合您。下面是一个工作示例。

首先,将放入宽格式,并将列的顺序与所需的 table 一致。 然后,将对齐设置为 c(居中)并隐藏列名。使用 add_header_above 会给你 3 层 header。使用的数字表示 header 相对于下方列的 width/span。

library(tidyverse)
library(kableExtra)

df %>%
  pivot_wider(id_cols = cohort, names_from = c(category, gender), values_from = c(frequency, n)) %>%
  select(cohort, frequency_population_male, frequency_sample_male, frequency_population_female, frequency_sample_female,
         n_population_male, n_sample_male, n_population_female, n_sample_female) %>%
  mutate_if(is.numeric, format, digits=2) %>%
  kable(align = rep('c', 9), col.names = NULL) %>%
  kable_classic() %>%
  add_header_above(c("Cohort", rep(c("Population", "Sample"), 4))) %>%
  add_header_above(c(" ", "Male" = 2, "Female" = 2, "Male" = 2, "Female" = 2)) %>%
  add_header_above(c(" ", "Frequency" = 4, "N" = 4))

输出