Home > database >  Is there a way to specify flextable header labels by just listing the new header names in order?
Is there a way to specify flextable header labels by just listing the new header names in order?

Time:12-15

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.

CodePudding user response:

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

CodePudding user response:

From the docs the values argument has to be

a named list (names are data colnames), each element is a single character value specifying label to use.

One option to achieve your desired result would be to make use of setNames.

Additionally I make use of ft$col_keys[seq(length(values)) to get the column names of your ft table object.

library(flextable)

values <- c("SEPAL LENGTH", "SEPAL WIDTH", "PETAL LENGTH", "PETAL WIDTH")

ft <- flextable(head(iris))
ft <- set_header_labels(ft,
  values = setNames(values, ft$col_keys[seq(length(values))])
)
ft

Created on 2021-12-14 by the reprex package (v2.0.1)

  • Related