【问题标题】:Shiny modules: how to access selected_rows with DT::datatables?闪亮的模块:如何使用 DT::datatables 访问 selected_rows?
【发布时间】:2020-05-07 04:17:35
【问题描述】:

当使用闪亮的模块和 DT::datatable 时,我想访问 selected_rows 服务器端。 如果我的 DT:datatable ID 是 my_DT_table,那么我希望对象 input$my_DT_table_selected_rows 包含所选行的索引。 这在没有模块的闪亮应用程序中非常有效。

但是,如果我使用模块,则此方法不再有效,输入对象 input$my_DT_table_selected_rows 不再包含所选行的索引。

【问题讨论】:

    标签: r shiny dt shinymodules


    【解决方案1】:

    使用 DT:datatable 函数时,我们可以使用内置功能来了解 UI 中的选定行。

    对象:input$my_DT_table_rows_selected 包含所选行的索引,其中my_DT_table 是 DT::datatable 的 ID。

    但是,在使用模块时,表的名称现在不同了。它的前缀等于用于调用模块 UI 功能的 ID。 因此,如果该 ID 为 my_ID,则表名将变为:my_ID-table_name(注意 ID 后面的连字符)。 这可以使用浏览器中的开发人员工具(例如 FireFox 中的检查器)轻松验证。 然后关联的输入对象名称变为(我们需要反引号以防止 R 将连字符解释为减号):

    input$`my_ID-table_name_rows_selected`
    

    这是一个非常基本的示例,其中包含一些关于如何将反应对象传递给模块的额外学习。反应对象包含所选行的索引。我需要在没有括号的情况下通过它。在 module_server 函数内部,我用括号指代反应性对象。

    UI 模块 in ui_module.R

    module_ui <- function(id) {
      ns <- NS(id) # create namespace
    
      tagList(
        fluidRow(column(6, DT::dataTableOutput(ns("dt_table")))),
        fluidRow(column(4, verbatimTextOutput(ns("render_selected_line"))))
      )
    }
    

    服务器模块在 server_module.R

    table_server <- function(input, output, session, data) {
    
      output$dt_table <- DT::renderDataTable(
        DT::datatable(
        data = data,
        selection = "single"
        )
      )
    }
    
    selected_line_server <- function(input, output, session, data) { 
      output$render_selected_line <- renderText({
        paste0("My selection was: ", data()) # refer to the reactive object with parenthesis
      })
    
    }
    

    闪亮的应用程序

    library(shiny)
    library(dplyr)
    library(DT)
    
    source("./modules/ui_module.R")
    source("./modules/server_module.R")
    
    ui <- fluidPage(
      module_ui("my_ID")
    )
    
    server = function(input, output, session) {
      data <- mtcars
      callModule(table_server, id = "my_ID", data = data) # data is not reactive
      callModule(selected_line_server, id = "my_ID", data = selectedLine) # refer to the reactive object selectedLine without parenthesis
    
      selectedLine <- reactive({
        req(input$`my_ID-dt_table_rows_selected`)
        if (is.null(input$`my_ID-dt_table_rows_selected`)) {
          return(NULL)
        } else {
          rows_selected <- as.numeric(input$`my_ID-dt_table_rows_selected`) # we need to prefix dt_table_rows_selected with the ID of the UI function "my_ID" and a hyphen
        }
      })
    
    }
    
    shinyApp(ui = ui, server = server)
    

    【讨论】:

      猜你喜欢
      • 2020-09-30
      • 2019-10-25
      • 1970-01-01
      • 2017-12-09
      • 2016-10-25
      • 2020-09-18
      • 2017-05-05
      • 2020-01-18
      • 1970-01-01
      相关资源
      最近更新 更多