Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Row Headers with Flextable

Tags:

r

flextable

I'm having numerous issues attempting to format my table using flextable. As an example, the below table is what I'm starting with:

> df
   name   x1   x2   x3   x1   x2   x3
1  <NA> 2010 2010 2010 2011 2011 2011
2 name1    1    1    1    1    1    1
3 name2    2    2    2    2    2    2
4 name3    3    3    3    3    3    3
5 name4    4    4    4    4    4    4
6 name5    5    5    5    5    5    5

What I'd like to do is have 2 headers - one where the year is merged for each of 3 sets of columns, and the other where the column names are the same every 3 columns. For example, I want it to look like this:

> df
   name x1   x2 x3 x1   x2 x3
1  <NA>    2010       2011   
2 name1  1    1  1  1    1  1
3 name2  2    2  2  2    2  2
4 name3  3    3  3  3    3  3
5 name4  4    4  4  4    4  4
6 name5  5    5  5  5    5  5

In addition, the year header would be above the x1,x2,x3 headers. The issue I'm having is how to designate two headers in R, and then how to merge multiple sets of 3 columns in flextable. I can merge the first set of columns (2010) using:

flextable(df) %>%
  merge_at(i = 1,j = c(2:4), part = "body")

But I am not sure how to do the above for more than one grouping. Additionally, since that row isn't designated a "header", the part that I have to designate is "body".

Any help or pointers in the right direction would be greatly appreciated!

like image 613
coderX Avatar asked Sep 02 '25 10:09

coderX


1 Answers

The flextable library provides the add_header_row function for this. With your df, the following should work.

    flextable(df) %>% 
      add_header_row(top = TRUE, values = c("", "2010", "2011"), colwidths = c(1,3,3))
like image 181
GGAnderson Avatar answered Sep 04 '25 01:09

GGAnderson