17

I would like to merge few rows in column in DT::datatable in shiny. Is it possible to do so?

Currently I am able to output which looks something like this:

enter image description here

But ideally I would like to merge the rows and want to output something like this:

enter image description here

Is it possible to merge rows like this in DT::datatable?

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
SBista
  • 7,479
  • 1
  • 27
  • 58
  • 1
    According to @yihue you cannot merge cells in datatables: https://github.com/rstudio/DT/issues/346 – Carl Sep 14 '16 at 14:40

2 Answers2

16

It is possible with the help of the datatables-rowsgroup library. Here is an example:

library(shiny)
library(DT)

dat <- iris[c(1,2,3,51,52,53,101,102,103), c(5,1,2,3,4)]

ui <- fluidPage(
  DTOutput("table")
)

server <- function(input, output){
  output[["table"]] <- renderDT({
    dtable <- datatable(dat, rownames = FALSE, 
                        options = list(
                          rowsGroup = list(0) # merge cells of column 1
                        ))
    path <- "U:/Data/shiny/DT/www" # folder containing dataTables.rowsGroup.js
    dep <- htmltools::htmlDependency(
      "RowsGroup", "2.0.0", 
      path, script = "dataTables.rowsGroup.js")
    dtable$dependencies <- c(dtable$dependencies, list(dep))
    dtable
  })
}

shinyApp(ui, server)

enter image description here

Stéphane Laurent
  • 75,186
  • 15
  • 119
  • 225
  • Great solution! Maybe adding this plugin in DT library would be a great feature, or maybe create an entirely new R library for DT plugins? – SBista Jun 10 '19 at 04:48
  • 1
    As a non-Javascript user, I have trouble following your advice. Could you clarify what I need to do between landing on the page you link to and including the code you suggest? – Nibood_the_slightly_advanced Sep 20 '19 at 12:47
  • @NBE Take a look at https://stackoverflow.com/questions/58028528/merge-columns-in-dtdatatable – Stéphane Laurent Nov 07 '19 at 17:33
  • This has been really helpful, though I was wondering if it's possible to tweak rowGroup so as to use two columns to merge duplicate cells? – Beeba Dec 17 '19 at 14:46
  • How to use rowsGroup with rowGroup. i.e. GROUP 1, GROUP 2, rowsGroup – kraggle May 06 '22 at 18:01
  • when you say "# folder containing dataTables.rowsGroup.js" what's that js file? where do I get it? – Angelo Aug 04 '23 at 16:14
3

hey as far as i know its not possible to do it in DT i have another way to make it happen.

 kable(c, align = "c") %>%
  kable_styling(bootstrap_options = "striped", full_width = F, position = "left",font_size = 12)%>%
  column_spec(1, bold = T) %>%
  collapse_rows(columns = 1, valign = "middle")

please try it and it works :)