Search code examples
rrowgroupingflextable

flextable: How to show group headings as the value only rather as the variable name: value


library(tidyverse)
library(flextable)

MWE

tib <- tibble(var_group = c("a", "a", "b", "c", "c", "c"),
              var = 1:6)

tib <- as_grouped_data(x = tib, groups = c("var_group"), columns = NULL)

as_flextable(tib) 

How can I remove the var_group: part of the grouped headings so that I am left with a, b, and c?

This is what I would like to see (not worried about hlines - it's the text that is important):

This is what I would like to see

Not this:

flextable default grouped rows


Solution

  • You need to use flextable::compose to be able to overwrite default values. It's important to look at the data produced by as_grouped_data that will be used. The groups have been added a dummy rows and we can use that column.

    library(tidyverse)
    library(flextable)
    #> 
    #> Attachement du package : 'flextable'
    #> The following object is masked from 'package:purrr':
    #> 
    #>     compose
    
    tib <- tibble(var_group = c("a", "a", "b", "c", "c", "c"),
                  var = 1:6)
    
    tib <- as_grouped_data(x = tib, groups = c("var_group"), columns = NULL)
    tib
    #>   var_group var
    #> 1         a  NA
    #> 4      <NA>   1
    #> 5      <NA>   2
    #> 2         b  NA
    #> 6      <NA>   3
    #> 3         c  NA
    #> 7      <NA>   4
    #> 8      <NA>   5
    #> 9      <NA>   6
    tib %>% 
      as_flextable( ) %>% 
      flextable::compose(
        i = ~ !is.na(var_group), # when var_group not NA
        j = "var", # on column "var"
        # create a paragraph containing a chunk containing value of `var_group`
        value = as_paragraph(as_chunk(var_group))) %>% 
      hline(i = ~ !is.na(var_group), border = officer::fp_border() ) %>% 
      autofit()
    

    enter image description here