rlistr-flextable

Adding titles to flextables in a list of lists


I have example data as follows (which is a list of lists of flextables):

library(data.table)
library(flextable)
datA <- fread("anyvar somevar
               2  4
               2  3
               2  5")

dat_list <- list("one" = list("datA" = datA, "datB" = 2*datA),"two" = list("datC" = 3*datA, "datD" = 4*datA), "three" = list("datE" = 5*datA, "datF" = 6*datA))

for (i in seq_along(dat_list) ) {
  for (j in seq_along( dat_list[[i]] ) ) {
    dat_list[[i]][[j]] <- flextable( dat_list[[i]][[j]] )
  }
}

vector_of_lists <- c("one", "two", "three")

Attempt

I want to add titles to each flextable one, two, three.

for (i in seq_along(dat_list) ) {
  for (j in seq_along( dat_list[[i]] ) ) {
    dat_list[[i]][[j]] <- add_header_row(dat_list[[i]][[j]],  top = TRUE, values = paste0("Table: ", i, " Header of table", vector_of_lists[i] ))
  }
}

The error I get is:

Error in inverse.rle(structure(list(lengths = colwidths, values = values), :
   invalid 'rle' structure

Desired output:

Something like below, but then with: "Table 1: Header of table one"

enter image description here


Solution

  • Changing the code from add_header_row() to set_caption() works

    for (i in seq_along(dat_list) ) {
      for (j in seq_along( dat_list[[i]] ) ) {
        dat_list[[i]][[j]] <- set_caption(dat_list[[i]][[j]], caption = paste0("Table: ", i, " Header of table", vector_of_lists[i] ))
      }
    }
    
    dat_list[[3L]][[1L]]
    

    HTML table of caption added to R flextable

    The issue was that add_header_rows() generally wants the user to include a named character vector that matches the column names that you want additional header information for. To at least get your original approach from not erroring, you could have specified that the colwidths = 2 where 2 is the number of columns of your table.

     for (i in seq_along(dat_list) ) {
       for (j in seq_along( dat_list[[i]] ) ) {
         dat_list[[i]][[j]] <- add_header_row(dat_list[[i]][[j]], top = TRUE,colwidths = 2,values = paste0("Table: ",i," Header of table",vector_of_lists[i] ))
       }
     }
    
    dat_list[[3L]][[1L]]
    

    The styling is slightly different as now we have two rows of headers instead of a header and a title.

    HTML table header row inserted for R flextable