Search code examples
rtidyverseflextable

Correctly align footers with flextable()


Is there a way that I can apply different alignments to a footer row in a flextable object? In the example below, I would like the first cell of the footer row to be left-aligned and the rest of the cells to be center-aligned. Thank you.

library(tidyverse)
df<-data.frame(
  var1=rep(c('A', 'B'), 10),
  var2=rep(c('apples', 'oranges'), 10), 
  var3=rnorm(20),
  var4=rnorm(20), 
  var5=rnorm(20))
library(flextable)
flextable(df) %>% 
  add_footer_row(values=c('nobs', nrow(df), nrow(df), nrow(df)), colwidths=c(2,1,1,1)) %>% 
  align(., align="center", part="footer")

Solution

  • Is this what you are after? Apply align twice but in order. align(align = "center", part = "footer") first to center the whole footer and then once more just to pick out the cell you want: align(i = NULL, j = 1, align = "left", part = "footer")

    library(tidyverse)
    library(flextable)
    df <- data.frame(
      var1=rep(c('A', 'B'), 10),
      var2=rep(c('apples', 'oranges'), 10), 
      var3=rnorm(20),
      var4=rnorm(20), 
      var5=rnorm(20))
    flextable(df) %>% 
      add_footer_row(values = c('nobs', nrow(df), nrow(df), nrow(df)), colwidths=c(2, 1, 1, 1)) %>% 
      align(align = "center", part = "footer") %>% 
      align(i = NULL, j = 1, align = "left", part = "footer")