I'm looking at this previous question Collapse rowGroup Shiny and the solution provided.
library(shiny)
library(DT)
ui <- fluidPage(# Application title
titlePanel("Collapse/Expand table"),
mainPanel(DTOutput("my_table")))
callback_js <- JS(
"table.on('click', 'tr.dtrg-group', function () {",
" var rowsCollapse = $(this).nextUntil('.dtrg-group');",
" $(rowsCollapse).toggleClass('hidden');",
"});",
"table.one('init', () => $('#my_table .dtrg-group').trigger('click'))"
)
server <- function(input, output) {
output$my_table <- DT::renderDT({
datatable(
mtcars[1:15, 1:5],
extensions = 'RowGroup',
options = list(rowGroup = list(dataSrc = 2), pageLength = 20),
callback = callback_js,
selection = 'none'
)
})
}
# Run the application
shinyApp(ui = ui, server = server)
I managed to enhance the JS such that the wakeup view of this table is collapsed. Data in this example is collapsed based off dataSrc = 2 that corresponds to the 2nd column of the mtcards table, that is, the 'cyl' column. What I need: I would need to be able to see the count of cars for each cyl category when the table is collapsed. How can I do that?
Here is one example where the count of each category is written into the collapsed row groups by editing the corresponding innerHTML
. You can get this by adding the following JS
to your callback.
table.on('init', () => $('#my_table .dtrg-group').each(function(i, obj) {
var grpcount = $(this).nextUntil('.dtrg-group').length.toString();
this.innerHTML = this.innerHTML.replace('</th>', ', count: ' + grpcount + '</th>');
}));"
library(shiny)
library(DT)
ui <- fluidPage(# Application title
titlePanel("Collapse/Expand table"),
mainPanel(DTOutput("my_table")))
callback_js <- JS(
"table.on('click', 'tr.dtrg-group', function () {",
" var rowsCollapse = $(this).nextUntil('.dtrg-group');",
" $(rowsCollapse).toggleClass('hidden');",
"});",
"table.one('init', () => $('#my_table .dtrg-group').trigger('click'))",
"table.on('init', () => $('#my_table .dtrg-group').each(function(i, obj) {",
" var grpcount = $(this).nextUntil('.dtrg-group').length.toString();",
" this.innerHTML = this.innerHTML.replace('</th>', ', count: ' + grpcount + '</th>');",
"}));"
)
server <- function(input, output) {
output$my_table <- DT::renderDT({
datatable(
mtcars[1:15, 1:5],
extensions = 'RowGroup',
options = list(
rowGroup = list(dataSrc = 2),
pageLength = 20
),
callback = callback_js,
selection = 'none'
)
})
}
# Run the application
shinyApp(ui = ui, server = server)