Gaurav Bansal Gaurav Bansal -4 years ago 114
R Question

Looping to create tabs in tabsetPanel in 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)

Answer Source

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))
                  )
                })))
    )
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download