Search code examples
rflextable

r can't read dput output back in


The code and associated dput output generate a table header that has two rows. The top row has the original column names. the second row is the new column names. I'd like to display only the second row. How can I turn off/hide the first row?

library(flextable)
library(stringr)
d <- structure(list(ISO3 = c("AFG", "AGO", "ALB", "AND", "ARE", "ARG", "ARM", "AUS", "AUT", "AZE"), Name = c("Afghanistan", "Angola", "Albania", "Andorra", "United Arab Emirates", "Argentina", "Armenia", "Australia", "Austria", "Azerbaijan"), `annual_historical_1991-2010` = c(96, 84, 96, 98, 77, 93, 97, 88, 98, 94), `annual_ssp126_2041-2060` = c(94, 80, 94, 97, 71, 92, 96, 85, 97, 92), `annual_ssp126_2081-2100` = c(94, 80, 94, 97, 72, 92, 96, 85, 97, 91), `annual_ssp585_2041-2060` = c(93, 78, 93, 96, 69, 91, 95, 83, 97, 91), `annual_ssp585_2081-2100` = c(89, 69, 88, 93, 57, 87, 91, 77, 94, 85), `hot90_historical_1991-2010` = c(89, 76, 88, 94, 58, 87, 91, 76, 95, 83), `hot90_ssp126_2041-2060` = c(85, 71, 82, 90, 50, 84, 86, 72, 92, 77), `hot90_ssp126_2081-2100` = c(85, 71, 82, 90, 50, 84, 86, 72, 92, 76), `hot90_ssp585_2041-2060` = c(83, 68, 79, 88, 46, 82, 84, 70, 90, 74), `hot90_ssp585_2081-2100` = c(73, 56, 67, 79, 31, 75, 73, 59, 83, 60), `season_historical_1991-2010` = c(96, 84, 95, 98, 76, 93, 97, 92, 98, 93), `season_ssp126_2041-2060` = c(94, 81, 92, 96, 71, 91, 95, 90, 97, 91), `season_ssp126_2081-2100` = c(94, 80, 92, 96, 72, 91, 95, 90, 97, 90), `season_ssp585_2041-2060` = c(93, 78, 91, 95, 69, 90, 94, 89, 96, 89), `season_ssp585_2081-2100` = c(88, 69, 85, 91, 58, 86, 90, 84, 93, 84)), row.names = c(2L, 3L, 5L, 6L, 7L, 8L, 9L, 14L, 15L, 16L), class = "data.frame")

col_labels <- str_replace(names(d), "_ssp126_", " SSP1-2.6, ") |> 
  str_replace("_ssp585_", " SP5-8.5, ") |>
  str_replace("_historical_", " Historical, ") |>
  str_replace("annual ", "") |> 
  str_replace("hot90 ", "") |> 
  str_replace("season ", "")

names_list <-  as.list(setNames(col_labels, names(d)))

t_flex <- as_flextable(d)  |>
  set_header_labels(values = names_list)
t_flex

Solution

  • From the docs (?as_flextable.data.frame):

    It displays the first rows and shows the column types.

    Also, set_header_labels

    set(s) labels for specified columns in the bottom row header of a flextable.

    Hence, the issue is that as_flextable will give you a table with a two row header where the second or bottom row contains the datatypes which are then replaced by you labels via set_header_labels.

    Instead you could use flextable():

    library(flextable)
    
    flextable(d) |>
      set_header_labels(values = names_list)
    

    enter image description here