Search code examples
rflextable

Group/Merge values as header in flextable


I have a dataset similar to this

mydf<-data.frame(
  estimate=rep(c("b0","b1","b2"),2),
  linear=rep(c("0.1(0.1)*","0.1(0.1)*",""),2),
  quadratic=rep(c("0.1(0.1)*","0.1(0.1)*","0.1(0.1)*"),2),
  zone=c(rep("A",3),rep("B",3))
)

I would like to create a flextable similar to this pivot_wider result but with the columns linear and quadratic merged for each zone

mydf%>%
pivot_wider(names_from=zone,values_from=c(linear,quadratic))

The function merge_v does it by row, but what I need is to put the merged cells as merged headers.


Solution

  • There are various methods for that, I like this one because it works well with dplyr/tidyr:

    
    mydf<-data.frame(
      estimate=rep(c("b0","b1","b2"),2),
      linear=rep(c("0.1(0.1)*","0.1(0.1)*",""),2),
      quadratic=rep(c("0.1(0.1)*","0.1(0.1)*","0.1(0.1)*"),2),
      zone=c(rep("A",3),rep("B",3))
    )
    
    mydf%>%
      pivot_wider(names_from=zone,values_from=c(linear,quadratic)) |> 
      flextable::flextable() |> 
      flextable::separate_header() |> 
      flextable::align(align = "center", part = "all")
    
    

    enter image description here