Reset row selection for DT :: renderDataTable () in Shiny R
I have reproduced an example of a brilliant app written by Yihui Xie ( https://yihui.shinyapps.io/DT-rows/ ). The application uses DT::renderDataTable()
which allows you to select a row.
Everything works perfectly. I was wondering if it is possible to reset the select row (i.e. deselect the click)? I've already tried it with the reset action button s = input$x3_rows_selected
(see below script).
With my current script, it s = input$x3_rows_selected
does clean up, but I can't replenish it. Also the selected lines are still pressed (shaded)
Does anyone have any ideas? Is there an option in DT :: renderDataTable () to reset the selection? Or does anyone have an idea for a workaround?
Thank!
Example form https://yihui.shinyapps.io/DT-rows/ ) with my modification (action button):
server.R
library(shiny)
library(DT)
shinyServer(function(input, output, session) {
# you must include row names for server-side tables
# to be able to get the row
# indices of the selected rows
mtcars2 = mtcars[, 1:8]
output$x3 = DT::renderDataTable(mtcars2, rownames = TRUE, server = TRUE)
# print the selected indices
selection <- reactive({
if (input$resetSelection)
vector() else input$x3_rows_selected
})
output$x4 = renderPrint({
if (length(selection())) {
cat("These rows were selected:\n\n")
output <- selection()
cat(output, sep = "\n")
}
})
})
ui.R
library(shiny)
shinyUI(
fluidPage(
title = 'Select Table Rows',
h1('A Server-side Table'),
fluidRow(
column(9, DT::dataTableOutput('x3')),
column(3, verbatimTextOutput('x4'),
actionButton('resetSelection',
label = "Click to reset row selection"
) # end of action button
) #end of column
)))
source to share
Here's a possible solution, maybe not the best, but it works. It's based on re-creating the data every time the action button is pressed, so the selected rows are deleted.
library(shiny)
library(DT)
runApp(list(
server = function(input, output, session) {
mtcars2 = mtcars[, 1:8]
output$x3 = DT::renderDataTable({
# to create a new datatable each time the reset button is clicked
input$resetSelection
mtcars2
}, rownames = TRUE, server = TRUE
)
# print the selected indices
selection <- reactive ({
input$x3_rows_selected
})
output$x4 = renderPrint({
if (length(selection())) {
cat('These rows were selected:\n\n')
output <- selection()
cat(output, sep = '\n')
}
})
},
ui = shinyUI(fluidPage(
title = 'Select Table Rows',
h1('A Server-side Table'),
fluidRow(
column(9, DT::dataTableOutput('x3')),
column(3, verbatimTextOutput('x4'),
actionButton( 'resetSelection',label = "Click to reset row selection")
) #end of column
)
))
))
source to share