R Shiny dynamic tab number and input generation

2020-05-02 11:51发布

I've got an issue with my current shiny code. I have to generate a dynamic number of tabs depending on the results of a given function (that part works fine). Then, I want to generate the input of these tabs in other loops of for example renderText. However, the final output of the textOutput for my generated renderText is always the one of the last renderText of the loops.

Here is a small example of the idea:

 library(shiny)
 library(shinydashboard)


 ui <- pageWithSidebar(
         headerPanel("xxx"),
         sidebarPanel(),
         mainPanel(
           uiOutput("multipleUI")
         )
      )


server <- function(input, output) {
      output$multipleUI <- renderUI({
      tabs <- list(NULL)
      for(i in 1:5){
          tabs[[i]] <- tabPanel(title = paste0("tab ",i),
                      textOutput(paste0("out",i)), # prints j as 5 in all tabs
                      paste0("local out ",i)) # prints i as current loop value for each tab)
     }
     do.call(tabBox,tabs)
  })
  observe({ 
    for(j in 1:5){ 
      txt = paste0("generated out ", j)
      print(txt) # print with current j
      output[[paste0("out",j)]] <- renderText({txt})
    }
  })
}

shinyApp(ui, server)

While it might not be that important for renderText where I can just work around the issue, I intend to render a lot of plots and tables and couldn't think of a workaround there.

I'd appreciate any help!

EDIT: I've updated the code to show a small working example

标签: r loops shiny
1条回答
Deceive 欺骗
2楼-- · 2020-05-02 12:01

Here's a solution that seems to work. I'm using lapply to create the tabs. Let me know if it works for what you need.

library(shiny)

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

server <- function(input, output) {     
  lapply(1:5, function(j) {
    output[[paste0('out',j)]] <- renderPrint({
      paste0('generated out ', j)
    })
  })
}

shinyApp(ui, server)
查看更多
登录 后发表回答