KableExtra html table not collapsing rows

Viewed 22

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

1 Answers

Given this issue seems to have been persistent with the kbl (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

Related