在Shiny模块中选择DataTable行

5

我正在尝试将这个基本的可用shiny应用程序进行模块化。这是有效的:

shinyApp(
  ui = fluidPage(
    DT::dataTableOutput("testTable"),
    verbatimTextOutput("two")
  ),
  server = function(input,output) {
    output$testTable <- DT::renderDataTable({
      mtcars
    }, selection=list(mode="multiple",target="row"))

    output$two <- renderPrint(input$testTable_rows_selected) 
  }
)

我希望将这个模块制作成适用于任何数据框的模块。

# UI element of module for displaying datatable
testUI <- function(id) {
  ns <- NS(id)
  DT::dataTableOutput(ns("testTable"))

}
# server element of module that takes a dataframe
# creates all the server elements and returns
# the rows selected
test <- function(input,output,session,data) {
  ns <- session$ns
  output$testTable <- DT::renderDataTable({
    data()
  }, selection=list(mode="multiple",target="row"))

  return(input[[ns("testTable_rows_selected")]])

}

shinyApp(
  ui = fluidPage(
    testUI("one"),
    verbatimTextOutput("two")
  ),
  server = function(input,output) {
    out <- callModule(test,"one",reactive(mtcars))
    output$two <- renderPrint(out()) 
  }
)

这给我带来了错误,说我正在尝试在非响应式环境下使用反应性。如果我消除返回语句,它就可以运行。是否有任何方法可以从闪亮的模块中返回选择的数据表行?任何帮助将不胜感激。


谢谢,你的评论帮我想通了。 - Carl
2个回答

4

Needed

return(reactive(input$testTable_rows_selected))

0

由于您提供的问题和答案仍然非常相关,我想就使用shiny模块更新代码进行说明:

testUI <- function(id) {
  tagList(
    DT::dataTableOutput(NS(id, "mytable")),
    verbatimTextOutput(NS(id, "selected"))
  )
}

testServer <- function(id) {
  moduleServer(id, function(input, output, session) {
    output$mytable <- DT::renderDataTable({
      mtcars
    }, selection = list(mode = "multiple", target = "row"))
    
    output$selected <- renderPrint(
      input$mytable_rows_selected  # Caution: The prefix must match the id of my namespace
    )
    
  })
}


testApp <- function() {
  ui <- fluidPage(
    testUI("test")
  )
  server <- function(input, output, session) {
    testServer("test")
  }
  shinyApp(ui, server)  
}

testApp()

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