Shiny - populate static HTML table with filtered data based on input

前端 未结 1 1692
独厮守ぢ
独厮守ぢ 2021-01-22 15:08

I am currently working on a Shiny app which displays a static HTML table, sourced from another file, because of the size of the HTML code. The table is initialized with an empty

相关标签:
1条回答
  • 2021-01-22 15:33

    I found a solution to my problem!

    The static html table is wraped in a function, which will be sourced once on startup in the server part of the app and then called in the renderUI() function. The render-function will be triggered every time a user changes the menu. Here I filter the dataframe regarding to the input and pass it to the "build_table" function. Each cell of the table is then populated with the needed values from the dataframe via indexes. The function return the full html table back to the renderUI().

    This is the toy example from above, adjusted to the working solution:

    app.R

    library(shiny)
    
    ui <- fluidPage(
    
      fluidRow(
               column(width = 6, uiOutput("cars"))
      ),
      fluidRow(
        column(width = 6, htmlOutput("html.table"))
      )
    )
    
    server <- function(input, output) {
    
      source("server_html_table.R",  local = TRUE)
    
      output$cars <- renderUI({
        selectizeInput(
          inputId = "cars",
          label = NULL,
          choices = rownames(mtcars),
          options = list(placeholder = 'Cars')
        )
      })
    
      output$html.table <- renderUI({
    
        input$cars
    
        isolate({
    
          filtered_cars <- subset(mtcars, rownames(mtcars) %in% input$cars)
    
          build_table(filtered_cars)
        })
      })
    }
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    server_html_table.R

    build_table <- function(data){
    
      html.table <- tags$table(style = "border: 1px solid black; padding: 1%; width: 100%;",
                              tags$tr(
                                      tags$th("Car Name"),
                                      tags$th("MPG"),
                                      tags$th("CYL"),
                                      tags$th("DISP"),
                                      tags$th("HP")
    
                              ),
                              tags$tr(
                                      tags$td(rownames(data)),
                                      tags$td(data$mpg),
                                      tags$td(data$cyl),
                                      tags$td(data$disp),
                                      tags$td(data$hp)
                             )
                      )
    
      return(html.table)
    }
    
    0 讨论(0)
提交回复
热议问题