Search code examples
rlatexkableextra

kableExtra - collapse_rows not working when linebreaks are present


As stated in the title, the collapse_rows function of kableExtra doesn't seem to work when linebreaks are present. Examples below will hopefully explain clearly.

df <- data.frame(A = rep("abc", 3), B = c(1,2,3))

table <- kable(df, format = "latex") %>%
    collapse_rows(columns = 1, valign = "middle")

table

will produce:

collapse_rows without linebreaks

But

df <- data.frame(A = linebreak(rep("a\nb\nc", 3)), B = c(1,2,3))

table <- kable(df, format = "latex", escape = FALSE) %>%
    collapse_rows(columns = 1, valign = "middle")

table

produces:

collapse_rows with linebreaks

The only difference between the two code chunks being that in the second code chunk linebreak is wrapping the A column, \n is added two times to the string "abc" to make it "a\nb\nc", and escape = FALSE is added as an argument to the kable call.

I would still very much like them to collapse into a single cell. Does anyone know how to fix this?

Best regards


Solution

  • The problem is the linebreak() call, which applies different alignment to each of the three occurrences of the label, so collapse_rows() doesn't see them as the same thing. That's probably a bug in the function, but it has an easy workaround: just specify the alignment explicitly:

    df <- data.frame(A = linebreak(rep("a\nb\nc", 3), align = "c"), 
                     B = c(1,2,3))
    
    table <- kable(df, format = "latex", escape = FALSE) %>%
        collapse_rows(columns = 1, valign = "middle")
    
    table
    

    enter image description here

    Edited to add: I just noticed that this was fixed in the devel version of kableExtra, but there hasn't been a new release in quite a while. So your original code should work if you install the devel version using

    remotes::install_github("haozhu233/kableExtra")