【问题标题】:assign output ID to renderdataTable() objects in lapply in shiny在闪亮的 lapply 中将输出 ID 分配给 renderdataTable() 对象
【发布时间】:2018-06-26 09:13:19
【问题描述】:

我有一个列表,其中包含几个相同格式的 data.frames,我想用这些 data.frames 制作一个 tablist,将每个 data.frame 显示为 DT::datatable 并在其中绘制下面,以下代码可以正常工作:

createTabs <- function(df) {
    tabPanel(
             renderDataTable(df),
             renderPlotly(volcano_plot(df))
    )}

myTabs <- lapply(myList, createTabs)
return(do.call(tabsetPanel,myTabs))

但是,这种方式我没有为每个 renderDataTable 对象分配输出 ID,以后如果我想让用户选择的行在数据表中做一些统计,就像在这个一样

How do I get the data from the selected rows of a filtered datatable (DT)?

这是不可能的,因为我无法获得这些数据表的输出 ID,我想知道是否有办法在我使用 renderDataTable() 创建时为每个数据表分配一个输出 ID,或者是否有还有其他方法吗?欢迎任何想法!

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    您可以先构造输出对象(以便命名它们),然后在创建 tabsetPanel 时调用它们。工作示例:

    library(shiny)
    library(plotly)
    
    ui <- fluidPage(
      uiOutput('my_tabsetpanel')  
    
    )
    
    server <- function(input, output, session) {
    
      myList = list('dt_1'= head(mtcars,5), 'dt_2' = head(mtcars,5), 'dt_3'= head(mtcars,5))
    
      # create the tables
      lapply(seq_along(myList),function(x) {
        output[[names(myList)[x]]] = renderDataTable({myList[[x]]})
      })
    
      # create the plots
      lapply(seq_along(myList),function(x) {
        output[[paste0(names(myList)[x],'_plot')]] = renderPlotly({plot_ly(myList[[x]],x=~mpg,y=~cyl)})
      })  
    
      # create tabsetPanel 
      output$my_tabsetpanel <- renderUI({
        myTabs = lapply(seq_along(myList), function(x)
        {
          tabPanel(paste0('mytab',x),
                   dataTableOutput(names(myList)[x]),
                   plotlyOutput(paste0(names(myList)[x],'_plot')))}
        )
        do.call(tabsetPanel, myTabs)
      })
    }
    
    shinyApp(ui, server)
    

    现在您还可以调用它们选择的行,因为数据表已命名。如果MyList 实际上是反应式的,则应将observer 包裹在两个lapply 语句周围。希望这会有所帮助!

    【讨论】:

    • 很好的答案,我不知道实际上可以将 tabPanel 放在函数中,这很神奇,谢谢:D
    猜你喜欢
    • 2017-05-25
    • 2018-05-02
    • 2020-09-18
    • 2021-11-21
    • 1970-01-01
    • 2019-03-20
    • 2021-04-19
    • 2014-02-28
    • 1970-01-01
    相关资源
    最近更新 更多