Alokin
Alokin

Reputation: 505

KableExtra html table not collapsing rows

I have a simple Table that I want to visualize in an html format using kableExtra. This table has a few repeated cells in the first column and I would like to collapse these cells into one. Only problem is that the package isn't letting me do that. How can I solve this?

This is my data:

df <- data.frame( Vegitation  = c("Tree", "Tree", "Tree" , "Fruit", "Fruit", "Water"),
              Non_sense_var1 = c(17,14,1,20,21,0),
              Non_sense_var2 = c(15,1,11,2,2.1,60),
              Non_sense_var3 = c(4,6,14,2,7,7)
              )

And this is the code for my table:

header_line <- c("Vegitation", "Value 1", "Value 2", "Value 3")



kbl(df, escape = F, align = 'lcccc')%>%
add_header_above( header_line, bold = T, line = F, font_size = 11) %>%
kable_styling(full_width = T, font_size = 10, html_font = 'arial') %>%
kable_classic() %>%
column_spec(1, width = "2.2cm", bold = TRUE ) %>%
column_spec(2, width = "2.2cm") %>%
column_spec(c(3:4), width = "2.2cm",  color = '#FF7F0E') %>%
collapse_rows(1, valign = "top") 

And when I try to run this code, this is what I get:

enter image description here

EDIT: Currently (the date being Sept. 27 2022), KableExtra has issues when collapsing rows in similar scenarios as to mentioned here. There is no official production fix in yet. You can try the fix via github update but what that did for me was mess up other formatting of my table. You can also try another package for your use case. As of now, those seem like the possible available options.

Upvotes: 1

Views: 920

Answers (1)

Susan Switzer
Susan Switzer

Reputation: 1922

Given this issue seems to have been persistent with the kbl (https://github.com/haozhu233/kableExtra/issues/624), you may consider another package such as reactable, huxatable, or gt

a couple of examples:

df <- data.frame( Vegitation  = c("Tree", "Tree", "Tree" , "Fruit", "Fruit", "Water"),
                  Non_sense_var1 = c(17,14,1,20,21,0),
                  Non_sense_var2 = c(15,1,11,2,2.1,60),
                  Non_sense_var3 = c(4,6,14,2,7,7)
)


header_line <- c("Vegitation", "Value 1", "Value 2", "Value 3")


library(reactable)

reactable(df, 
          columns = list(
            Vegitation = colDef(
              style = JS("function(rowInfo, column, state) {
        const firstSorted = state.sorted[0]
        // Merge cells if unsorted or sorting by school
        if (!firstSorted || firstSorted.id === 'Vegitation') {
          const prevRow = state.pageRows[rowInfo.viewIndex - 1]
          if (prevRow && rowInfo.values['Vegitation'] === prevRow['Vegitation']) {
            return { visibility: 'hidden' }
          }
        }
      }"))))

library(gt)

df <- df %>% 
  group_by(Vegitation)
gt(df)

reactable example

gt example

Upvotes: 2

Related Questions