1

If I have a flextable without a header, how can I add one? In the example below I am setting the scenario up artificially. i.e. I would like to turn flexiris_without_head back into flexiris_with_head.

library(flextable) # version 0.9.2

flexiris_with_head <- flextable(iris)
flexiris_with_head

flexiris_without_head <- flexiris_with_head %>%
  delete_part(part = "header")
flexiris_without_head

If anyone is interested in more context:
I am primarily working with huxtable objects, which I, however, need to translate to flextable objects for docx output purposes. Using huxtable::as_flextable() leaves me without a (technical) header, which is an issue for long tables because the headers do not roll over to the next docx page anymore.

Patrick
  • 742
  • 7
  • 19
  • For the `huxtable` to `flextable` translation using `colnames_to_header = TRUE` in the `huxtable::as_flextable()` seems to do the trick. However, the header is duplicated in the first row then. – Patrick Jul 20 '23 at 08:13
  • Duplication of the header can be handled by running `slice(-1)` before running `huxtable::as_flextable(colnames_to_header = TRUE)`. – Patrick Jul 20 '23 at 09:01

1 Answers1

1

Here is one way how we could do it using add_header_row():

library(dplyr)
library(flextable)

# flextable
df <- flextable(head(iris))

# iris without header -> df
df_without_header <- df %>%
  delete_part(part = "header")

# adding header to flextable
df_with_header <- df_without_header %>%
  add_header_row(
    values = colnames(iris), 
    top = TRUE
  ) %>%
  hline_top(part = "header") %>%
  hline_bottom(part = "header")

df_with_header

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66
  • 1
    FWIW: I actually tried this function (`add_header_row()`) because I was sifting through the functional reference of `flextable` but never actually specified the `values` paramter in my piping which - as I see now - led to the values being fed into the `top` parameter, which then again led to an error. Not the most intuitive default ordering of parameters IMHO. – Patrick Jul 20 '23 at 08:43