Search code examples
rflextable

In R flextable how can I align columns below merged headers with autofit


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")

Solution

  • I'm not quiet familiar with the flextable package. But it worked for me when I aligned the table before merging the header. Maybe that's the trick.

      
      flextable(`Table 8.1`) %>%
        add_header_row(values = c("Pay Higher Taxes", 
                                  "Cut Living Standard", 
                                  "Cut Living Standard", 
                                  "Total")) %>%
        theme_booktabs() %>%
        autofit(part = "all") %>%
        align(align = "center", part = "all")%>% 
        merge_h(part = "header") %>%
        merge_v(part = "header") %>%
        set_caption(caption = "Table 8.1")  
        
    

    enter image description here