【发布时间】:2020-01-23 12:04:17
【问题描述】:
如何(或可以)调整使用kableExtra::add_header_above() 创建的表格中的标签?一个小例子:
library(knitr)
library(dplyr)
library(tidyr)
library(kableExtra)
df <- tibble(year = c(2017, 2018, 2017, 2018),
major_item = "M",
sub_item = c( "A", "A", "B", "B"),
n = c( 1:4))
df %>%
filter(sub_item == "A") %>%
select(-sub_item) %>%
spread(year,n) %>%
# now join with the part for which sub_item == "B"
left_join(df %>%
filter(sub_item == "B") %>%
select(-sub_item) %>%
spread(year,n),
by = c("major_item" = "major_item")) %>%
# now the nice header
kable("latex", booktabs = T) %>%
kable_styling() %>%
add_header_above(c(" " = 1, "A" = 2, "B" = 2))
结果是:
当然会出现后缀.x,因为有同名的列,一组是不允许的。 我该怎么做才能使 2017.x 和 2018.x 与其他列 2017 和 2018 相同? 任何关于如何以更少的步骤获得结果表的提示也非常受欢迎。谢谢!
2019_09_26 更新:感谢 pivot_wider,我找到了一种优雅的表格结构方式,并且感谢 iago,它具有所需的列名:
df %>%
# the table structure
pivot_wider(names_from = c(year, sub_item),
values_from = n) %>%
# the nice headings
kable("latex", booktabs = T,
col.names = c("", "2017", "2018", "2017", "2018")) %>%
kable_styling() %>%
add_header_above(c(" " = 1, "A" = 2, "B" = 2))
【问题讨论】:
-
在
kable中有一个选项col.names -
谢谢!没想到在
kable()找答案,全神贯注kableExtra()
标签: r r-markdown kableextra