Search code examples
rflextable

Merge horizontally only for certain columns flextable


I have the following table:

 tmp <- structure(list(SOC = c("Blood", "", "", "Gast", "", "", "", "Skin", 
                  "", "", "Adverse Event"), `Adverse Event` = c("Blood", "Raised Alt", "Raised Ast", 
                  "Gast", "Bloating", "Diarrhoia", "Vomiting", "Skin", "Reddness", 
                  "Rash", "Any Adverse Event"), C11 = c("", "0", "0", "", "0", 
                  "2", "0", "", "0", "0", "2"), C21 = c("", "0", "0", "", "1", 
                  "0", "1", "", "1", "0", "3"), T1 = c("", "0", "0", "", "1", "2", 
                  "1", "", "1", "0", "3"), C12 = c("", "1", "0", "", "0", "0", 
                  "0", "", "0", "1", "2"), C22 = c("", "0", "0", "", "0", "0", 
                  "1", "", "0", "0", "1"), T2 = c("", "1", "0", "", "0", "0", "1", 
                  "", "0", "1", "2"), C23 = c("", "0", "1", "", "0", "0", "0", 
                  "", "0", "0", "1"), T3 = c("", "0", "1", "", "0", "0", "0", "", 
                  "0", "0", "1"), C14 = c("", "1", "0", "", "0", "0", "0", "", 
                  "0", "0", "1"), T4 = c("", "1", "0", "", "0", "0", "0", "", "0", 
                  "0", "1")), row.names = c(NA, 11L), class = "data.frame")

I have turned it into a flextable like this:

 tmp %>% regulartable()

And now I am trying to horizontally merge the matching values ONLY in the SOC and Adverse Event columns.

I have tried using merge_h() but that doesn't give me the option to select certain columns, so it merges all of the other columns as well if there are duplicated values.

I have tried merge_at() but it doesn't work if all of the i and j values are not consecutive, which mine wont be.

Does anyone know of a way to only make merge_h() apply to certain columns? Or any other way of achieving what I'm after?

EDIT: I'm trying to make a flextable that looks a bit like this, but without any of the numeric columns being merged. As you can see in the bottom right hand corner all of the 1's have been merged. I just want the first two columns to merge so I can create the indentation effect.

enter image description here


Solution

  • You can create a for-loop iterating over the lines in question and then only merge the first two columns:

    lines <- c(1, 5, 7, 10)
    for (ll in lines){
      tmp <- merge_at(i = ll, j = 1:2, part = "body")
    }
    

    Might not be the most elegant, but it will do what you need