在 Shiny R 中重置 DT::renderDataTable() 的行选择

Reset row selection for DT::renderDataTable() in Shiny R

我复制了一个由 Yihui Xie (https://yihui.shinyapps.io/DT-rows/) 编写的闪亮应用程序示例。该应用程序使用 DT::renderDataTable() 允许行选择。

一切正常。但是我想知道是否可以重置行选择(即撤消点击选择)?我已经尝试使用操作按钮来重置 s = input$x3_rows_selected(请参阅下面的脚本)。

使用我当前的脚本,s = input$x3_rows_selected 确实会被清空,但我无法重新填充它。此外,选定的行仍被单击(阴影)

有人有想法吗? DT::renderDataTable() 中是否有重置选择的选项?或者有人有解决方法的想法吗?

谢谢!

示例表格 https://yihui.shinyapps.io/DT-rows/) 我的修改(操作按钮):

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
)))

这是一个可能的解决方案,也许不是最好的,但它确实有效。它基于每次单击操作按钮时重新创建数据表,因此删除了选定的行。

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
        )
    ))
))

current development version of DT (>= 0.1.16), you can use the method selectRows() to clear selections. Please see the section "Manipulate An Existing DataTables Instance" in the documentation.