格式化数据以使用kable在R标记中创建整洁的表格

格式化数据以使用kable在R标记中创建整洁的表格,r,r-markdown,kable,stargazer,R,R Markdown,Kable,Stargazer,我想使用kable包在R markdown中创建一个整洁的表,但我的数据需要转换 我的数据如下所示: category <- c('population', 'population', 'sample', 'sample', 'population', 'population', 'sample', 'sample') gender <- c('female', 'male', 'female', 'male', 'female', 'male', 'female', 'male')

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

我的数据如下所示:

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)

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

首先,将输入宽格式,并将列的顺序与所需的表一致。 然后,将对齐设置为
c
(居中)并隐藏列名。使用上面的
add_header_
将为您提供三层标题。使用的数字表示标题相对于下方列的宽度/跨度

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))
输出


在这种情况下,您可以试试kableExtra。如果有任何更具体的阻碍您使用kableExtra,请再次询问。