The officer set_header_labels function assigns a name to print replacing the column name, like this.
ft <- set_header_labels(ft,
values = list( Sepal.Length = "Sepal length", Sepal.Width = "Sepal width", Petal.Length = "Petal length", Petal.Width = "Petal width" )
I'd like to construct the pair of column name and replace dynamically. For example I have
cols_names <- c("colname1", "colnametitle1")
cols_titles <- c("colname2", "colnametitle2")
I want these to be output as
values = list( colname1 = "colnametitle1", colname2 = "colnametitle1" )
This gets close for the column names and titles pairs
paste0(cols_names, ' = "', cols_titles, '", "' )
But there must be some easier way manipulating lists that I haven't figured out.
CodePudding user response:
Unfortunately paste0
will not work as the values
argument of set_header_labels
requires a named list
. But you could use setNames
to do so.
Using a minimal reproducible example based on iris
:
library(flextable)
dat <- head(iris[1:2])
names(dat) <- c("colname1", "colname2")
ft <- flextable(dat)
cols_names <- c("colname1", "colname2")
cols_titles <- c("columntitle1", "columntitle2")
values <- setNames(cols_titles, cols_names)
ft <- set_header_labels(ft,
values = values
)
ft