1

I'm using flextable with a dataset that has many columns, and I want to use set_header_labels() to change them all at once, in order, without having to specify which name goes with each specific value. However, my code keeps running but not working. For instance, this code works:

library(flextable)
ft <- flextable( head( iris ))
ft <- set_header_labels(ft,
  values = list(Sepal.Length = "Sepal length",
                Sepal.Width = "Sepal width",
                Petal.Length = "Petal length",
                Petal.Width = "Petal width" ) )
ft

But this code doesn't change anything:

library(flextable)
ft <- flextable( head( iris ))
values <- c("SEPAL LENGTH", "SEPAL WIDTH", "PETAL LENGTH", "PETAL WIDTH")

ft <- set_header_labels(ft,
                        values = values)
ft

I'd like to just change the names in the dataframe, but that's not an option because in my actual table, the headers will have duplicate names (i.e., "2020", "2021", "2020", "2021", ...), which R won't allow.

aynber
  • 22,380
  • 8
  • 50
  • 63
J.Sabree
  • 2,280
  • 19
  • 48

1 Answers1

3

I see two suggestions for that.

You can use set_header_df if you can provide a data.frame where colnames are associated to labels.

library(flextable)
# suggestion 1: requires all names ----
ref_table <- data.frame(
  key = colnames(iris),
  label = c("SEPAL LENGTH", "SEPAL WIDTH", "PETAL LENGTH", "PETAL WIDTH", "SPECIES")
)
ft <- flextable( head( iris ))
ft <- set_header_df(ft, mapping = ref_table, key = "key")
ft <- theme_booktabs(ft)
ft

enter image description here

Or you can use setNames or names<- to make sure set_header_labels do its job (it's done by matching names (colkeys) and associated labels.

# suggestion 2: does not requires all names  ----
values <- setNames(c("SEPAL LENGTH", "SEPAL WIDTH", "PETAL LENGTH", "PETAL WIDTH"),
         colnames(iris)[-5]
)
ft <- flextable( head( iris ))
ft <- set_header_labels(ft, values = values)
ft

enter image description here

David Gohel
  • 9,180
  • 2
  • 16
  • 34
  • wow, thank you for taking the time to answer my question and for creating this awesome package! I didn't know that set_header_df() was an option--it solved my problem instantly. Thank you again--you've saved me many, many hours with this package! – J.Sabree Dec 14 '21 at 23:49
  • Is there really no way to set new column names just for "once" without constructing reference tables? Similar to `knitr::kable(x = mtcars, col.names = LETTERS[1:ncol(mtcars)])`? – Frederick Mar 07 '23 at 14:56
  • @Frederick see # suggestion 2 and if not easy enough open an issue – David Gohel Mar 07 '23 at 15:21
  • Please see: https://github.com/davidgohel/flextable/issues/517 – Frederick Mar 08 '23 at 15:26