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

10

我复制了Yihui Xie编写的一个shiny app示例 (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
)))
2个回答

13
在当前 DT 开发版本中(>= 0.1.16),您可以使用方法 selectRows() 来清除选择。请参阅 文档 中的“操作现有 DataTables 实例”一节。

列搜索过滤器也有解决方案吗? - ChriiSchee

1

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

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

谢谢,太好了!目前它对我来说已经做到了它的工作!如果有人知道一种实际重置选择的方法,我会很高兴知道! - ChriiSchee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接