Search code examples
rflextable

How do I center flextable in RMarkdown for loop?


I have the following Rmd doc that generates flextables within a for-loop and then prints out the tables. Im hoping to center the flextables within the html output. The issue is I keep getting all the tables as left aligned no matter what. I saw something about having to use flextable_html_dependency() but didnt see enough documentation for me to know how to properly use it.

---
title: "Test"
output: html_document
---

```{r, echo=FALSE, results='asis', fig.align='center'}
library(flextable)
library(tidyverse)

# Loop through data

overview_table <- function(df) {
  finalTable <- df %>%
  flextable() %>%
  set_header_labels(rowname = "") %>%
  theme_zebra() %>%
  bg(bg="#186183", part="body") %>%
  bg(bg="white", part="header") %>%
  color(part = "body", color = "white") %>%
  height(height = 0.4, part = "header") %>%
  padding(padding.top = 0,
          padding.bottom = 0) %>%
  fontsize(size = 20, part = "body") %>%
  fontsize(size = 18, part = "header") %>%
  align(align = "center", part = "all")
  return(finalTable)
}

for (i in 1:3) {
  
  cat('<center> <h1 style="font-size:80px;">', i, '</h1> </center> <br>')

  a <- overview_table(head(mtcars)[,1:4])
    
  flextable_to_rmd(a)
  cat("<br>")
}
```

Solution

  • You have to change your cat() statement so that the <center> opening and closing (</center>) HTML tag wraps around the table:

    
    for (i in 1:3) {
      
      cat('<center> <h1 style="font-size:80px;">', i, '</h1>')
    
      a <- overview_table(head(mtcars)[,1:4])
        
      flextable_to_rmd(a)
    
      cat("<br></center>")
    }
    

    enter image description here