How can I align flextable columns below merged headers with autofit?
08:36 05 Sep 2020

I am trying to replicate a table from a book using the flextable package in R. I have two columns below a header in a table marked with align(align = "center", part = "all") and they are not well aligned if I use autofit(part = "all").

enter image description here

Is there a way to fix this so the columns below the header are not offset to the right?

Here is the complete code:

Opinions <- read.table("http://users.stat.ufl.edu/~aa/cat/data/Envir_opinions.dat",
                       header = TRUE, stringsAsFactors = TRUE)
# Make contingency table
tab <- as.matrix(addmargins(xtabs(~y1 + y2, data = Opinions)))

library(tidyverse)  # for tibble()

# Add label as the first column and variable names
`Table 8.1` <- tibble(`Pay Higher Taxes` = c("Yes", "No", "Total"), 
                      Yes = tab[,1], No = tab[,2], Total = tab[,3])

library(flextable)
my_header <- data.frame(
  col_keys = colnames(`Table 8.1`),
  line1 = c("Pay Higher Taxes", rep("Cut Living Standards", 2), "Total"),
  line2 = colnames(`Table 8.1`)
)

library(flextable)
flextable(`Table 8.1`, col_keys = my_header$col_keys) %>%
  set_header_df(
    mapping = my_header,
    key = "col_keys"
  ) %>% 
  theme_booktabs() %>% 
  merge_h(part = "header") %>% 
  merge_v(part = "header") %>% 
  merge_h(part = "body") %>% 
  merge_v(part = "body") %>%
  align(align = "center", part = "all") %>% 
  autofit(part = "all") %>% 
  set_caption(caption = "Table 8.1")
r r-flextable