【问题标题】:Looping to create tabs in tabsetPanel in Shiny循环在 Shiny 的 tabsetPanel 中创建选项卡
【发布时间】:2017-07-21 06:22:12
【问题描述】:

我正在尝试使用 lapply 在 Shiny 中的 tabsetPanel 中创建多个选项卡,基于以下示例:http://shiny.rstudio.com/gallery/creating-a-ui-from-a-loop.html。下面是我的app.R 代码。当我运行它时,它不会创建 5 个选项卡,也不会打印每个选项卡的名称。我究竟做错了什么?

library(shiny)

ui <- pageWithSidebar(
  headerPanel("xxx"),
  sidebarPanel(),
  mainPanel(
    tabsetPanel(id='t',
      lapply(1:5, function(i) {
        tabPanel(
          title=paste0('tab', i), 
          textOutput(paste0('a',i))
        )
      }) 
    )
  )
)

server <- function(input, output) {
  observe({
    print(input$t)
  })

  lapply(1:5, function(j) {
    output[[paste0('a',j)]] <- renderPrint({
      input$t
    })
  })
}

shinyApp(ui, server)

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    这有点棘手,因为tabsetPanel 不接受tabset 的列表作为参数。您可以使用do.call 来“取消列出”参数:

    mainPanel(
        do.call(tabsetPanel, c(id='t',lapply(1:5, function(i) {
                      tabPanel(
                        title=paste0('tab', i), 
                        textOutput(paste0('a',i))
                      )
                    })))
        )
    

    【讨论】:

    【解决方案2】:
    stack.app <- function(n = 5){
    
      library(shiny)
    
      ui <- pageWithSidebar(
        headerPanel("xxx"),
        sidebarPanel(
          verbatimTextOutput("show_selected")
        ),
        mainPanel(
          uiOutput('my_tabs')
        )
      )
    
      server <- function(input, output, session) {
    
       output$my_tabs <- renderUI({
         ### Had to hicjack this from shiny to get it to work...
         shiny:::buildTabset(
           id = "t",
           lapply(1:n, function(i){
             tabPanel(title = sprintf("tt_%s",i),
                      HTML(sprintf("This is tab %s content", i))
             )
           }), paste0("nav nav-","tabs")) %>% (function(x){
             tags$div(class = "tabbable", x[[1]], x[[2]])
           })
       })
    
       output$show_selected <- renderPrint({
         sprintf("SELECTED TAB IS : %s", input$t)
       })
    
    
      }
    
      shinyApp(ui, server)
    
    }
    

    结果:

    【讨论】:

    • 干得好!但是,避免使用未导出的方法 ::: 通常是一个好习惯,因为它们可能不会在下一个版本中维护
    • 同意@HubertL;在看到您更简单的解决方案后,我面面相觑。我试图不惜一切代价避免do.call...所以我什至从未考虑过。
    猜你喜欢
    • 2018-06-21
    • 2014-05-20
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-14
    • 2023-04-09
    • 2020-10-09
    相关资源
    最近更新 更多