繁体   English   中英

闪亮的模块:如何使用 DT::datatables 访问 selected_rows?

[英]Shiny modules: how to access selected_rows with DT::datatables?

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

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

使用 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_module.R 中的UI 模块

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM