如何调整用 R kableExtra::add_header_above 创建的 table 中的标签?

How to adjust labels in table created with R kableExtra::add_header_above?

我如何(或我能否)调整使用 kableExtra::add_header_above() 创建的 table 中的标签?一个小例子:

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 年的其他列相同? 也非常欢迎任何有关如何以更少的步骤获得结果 table 的提示。谢谢!

更新 2019_09_26:感谢 pivot_wider,我找到了一种构建 table 的优雅方法,感谢 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))

我会做:

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, col.names = c("major_item","2017","2018","2017","2018")) %>%
  kable_styling() %>% 
  add_header_above(c(" " = 1, "A" = 2, "B" = 2))