My real data generate mutiple tables in a loop, and I would like to show them all in shiny.
When I am testing fake data, I am not able to generate a multiple tab table via for loop, here is my code:
library(shiny)
df1<-data.frame(matrix(ncol = 5,nrow = 10,data = runif(50,0,100),dimnames = list(1:10,paste0("S",1:5))))
ui <- fluidPage(
fluidRow(
tabsetPanel(
tabPanel("S1",tableOutput("S1")),
tabPanel("S2",tableOutput("S2")),
tabPanel("S3",tableOutput("S3")),
tabPanel("S4",tableOutput("S4")),
tabPanel("S5",tableOutput("S5"))
)
),
##not working here
fluidRow(
tabsetPanel(
for(i in 1:ncol(df1)){
tabPanel(title = paste0("S",i),tableOutput(outputId = paste0("test_S",i)))
}
)
)
)
server <- function(input, output) {
output$S1<-renderTable(df1[1])
output$S2<-renderTable(df1[2])
output$S3<-renderTable(df1[3])
output$S4<-renderTable(df1[4])
output$S5<-renderTable(df1[5])
##not woking here
for(i in 1:ncol(df1)){
id<-paste0("test_S",i)
output[[id]]<-renderTable(df1[i])
}
}
shinyApp(ui = ui, server = server)
The code generate noting in the for loop part, how do I revise the for loop part to generate the same result as my above table?
CodePudding user response:
I would try using lapply
to create your dynamic content in server
and not ui
. This will include renderUI
to create the dynamic number of tabs based on your data.frame (number of columns), and an observe
to dynamically create the renderTable
outputs. Let me know if this is what you had in mind.
library(shiny)
set.seed(42)
df1 <- data.frame(matrix(ncol = 5, nrow = 10, data = runif(50, 0, 100),
dimnames = list(1:10, paste0("S", 1:5))))
ui <- fluidPage(
uiOutput("mytabs")
)
server <- function(input, output) {
output$mytabs <- renderUI({
thetabs <- lapply(paste0('table_', seq_len(ncol(df1))),
function(x) {
tabPanel(x, tableOutput(x))
})
do.call(tabsetPanel, thetabs)
})
observe({
lapply(seq_len(ncol(df1)), function(x) {
output[[paste0("table_", x)]] <- renderTable({ df1[x] })
})
})
}
shinyApp(ui = ui, server = server)