簡體   English   中英

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

DT當前開發版本 (> = 0.1.16)中,您可以使用方法selectRows()來清除選擇。 請參閱文檔中的“操作現有DataTables實例”部分。

這是一個可能的解決方案,可能不是最好的,但它的工作原理。 它基於每次單擊操作按鈕時重新創建數據表,因此將刪除所選行。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM