LDT
LDT

Reputation: 3108

Show different data.frames in different tabs in a Shiny app

I have this super simple shiny app, and the main thing I want is to show in the MPG tab a table and a plot for df1; in the IRIS tab, I want to show a table and a plot for df2. My main problem is how I indicate in the server output that I want different data.frames in different tabs.

library(tidyverse)
library(shiny)

df1 <- mpg 
df2 <- iris

ui <- fluidPage(
  tabsetPanel(
    tabPanel("MPG", 
             dataTableOutput("dynamic"),
             plotOutput("plot", width = "400px")
    ), 
    tabPanel("IRIS", 
             dataTableOutput("dynamic"),
             plotOutput("plot", width = "400px"))
  )
)

server <- function(input, output, session) {
  
  output$dynamic <- renderDataTable(mpg, options = list(pageLength = 5))
  output$plot <- renderPlot(ggplot(df1) +
                              geom_bar(aes(x=manufacturer)) +
                              theme_bw())
  
  output$dynamic <- renderDataTable(iris, options = list(pageLength = 5))
  output$plot <- renderPlot(ggplot(df2) +
                              geom_bar(aes(x=Species)) +
                              theme_bw())
}

shinyApp(ui, server)
#> 
#> Listening on http://127.0.0.1:4563

Upvotes: 0

Views: 569

Answers (1)

LDT
LDT

Reputation: 3108

Thank you all for the comments! Just as a reference here is an answer that works based on your suggestions.

library(tidyverse)
library(shiny)

df1 <- mpg 
df2 <- iris

ui <- fluidPage(
  tabsetPanel(
    tabPanel("MPG", 
             dataTableOutput("table_one"),
             plotOutput("plot_one", width = "400px")
    ), 
    tabPanel("IRIS", 
             dataTableOutput("table_two"),
             plotOutput("plot_two", width = "400px"))
  )
)

server <- function(input, output, session) {
  
  output$table_one <- renderDataTable(mpg, options = list(pageLength = 5))
  output$plot_one <- renderPlot(ggplot(df1) +
                              geom_bar(aes(x=manufacturer)) +
                              theme_bw())
  
  output$table_two <- renderDataTable(iris, options = list(pageLength = 5))
  output$plot_two <- renderPlot(ggplot(df2) +
                              geom_bar(aes(x=Species)) +
                              theme_bw())
}

shinyApp(ui, server)

Upvotes: 2

Related Questions