Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping to create tabs in tabsetPanel in Shiny

Tags:

r

shiny

I'm trying to use lapply to create multiple tabs in a tabsetPanel in Shiny based on this example: http://shiny.rstudio.com/gallery/creating-a-ui-from-a-loop.html. Below is my app.R code. When I run it, it doesn't create 5 tabs, nor does it print the name of each tab. What am I doing wrong?

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)
like image 995
Gaurav Bansal Avatar asked Mar 01 '17 19:03

Gaurav Bansal


Video Answer


1 Answers

It's a bit tricky, because tabsetPanel does not accept a list of tabset as an argument. You can use do.call to "unlist" arguments:

mainPanel(
    do.call(tabsetPanel, c(id='t',lapply(1:5, function(i) {
                  tabPanel(
                    title=paste0('tab', i), 
                    textOutput(paste0('a',i))
                  )
                })))
    )
like image 52
HubertL Avatar answered Sep 30 '22 14:09

HubertL