Shiny: Merge cells in DT::datatable
Asked Answered
L

2

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?

Laconism answered 14/9, 2016 at 6:49 Comment(1)
According to @yihue you cannot merge cells in datatables: github.com/rstudio/DT/issues/346Shiloh
R
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

Residual answered 6/6, 2019 at 16:6 Comment(6)
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?Laconism
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?Mariammarian
@NBE Take a look at #58029028Expert
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?Ferdinana
How to use rowsGroup with rowGroup. i.e. GROUP 1, GROUP 2, rowsGroupTough
when you say "# folder containing dataTables.rowsGroup.js" what's that js file? where do I get it?Corybantic
G
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 :)

Gaming answered 23/5, 2019 at 9:33 Comment(1)
install. Packages('kableExtra')Gillard

© 2022 - 2024 — McMap. All rights reserved.