Creating tables in R shiny dynamically

I have a dataframe which I want to filter and create tables based on years in this case. I have 4 years now.So I would like to create 4 new tables and show them seperately on the shiny app.I do get the part of looping and pass the filter variables but how can that create 4 new tables and show them in the UI. As of now I am just displying the original df in the app.

    library(shiny)
library(shinyWidgets)
library(shinydashboard)
library(DT)

sidebar <- dashboardSidebar(
  sidebarMenu(id = "tab",
              menuItem("1", tabName = "1")
  )
)
body <-   ## Body content
  dashboardBody(box(width = 12,fluidRow(
    fluidRow(DT::dataTableOutput("op")))))

ui <-   dashboardPage(dashboardHeader(title = "Scorecard"),
                      sidebar,
                      body)

# Define the server code
server <- function(input, output,session) {
  df <- data.frame(structure(list(`Mazda` = c(21000,20000,21500,24000), `Honda` = c(21500,20500,22000,24500)
                                  ,  Sales = c(2014,2015,2016,2017)
                                  )
                             , class = "data.frame", row.names = c(NA, -4L)))


  output$op <-renderDataTable({ df })

}

shinyApp(ui = ui, server = server)

Right now, your shiny app will be completely static, since you haven't defined any UI inputs — is that what you intend?

If you do really want it to display four different static tables, one per year, then you need to do two things:

  1. Create places in the ui code for those outputs to show up using a table output function like tableOutput() or dataTableOutput — you've got one of these, but if you want 4 separate tables you'll need 4 of them.
  2. Write statements in the server code that tell shiny the recipe for rendering those outputs, using renderTable() or renderDataTable(). In this case, since these tables don't depend on inputs, the recipe will be the same code you'd use to filter the table outside of shiny.

Even though your app isn't really reactive right now (since there are no inputs), this example from the shiny gallery is still a good one to study to see how the basic design pattern of outputs works:
https://shiny.rstudio.com/gallery/reactivity.html

The Basic Data Table gallery example might also be helpful:
https://shiny.rstudio.com/gallery/basic-datatable.html

(all the shiny gallery apps run in showcase mode, which means that as you interact with them, the parts of the code that are firing show up highlighted in yellow — you can actually enable this for your own apps while testing! This can be a big help when you're trying to wrap your head around reactivity).

3 Likes