Aan de slagGa gratis aan de slag

Add an interactive table output

There are multiple htmlwidgets packages like DT, leaflet, plotly, etc. that provide highly interactive outputs and can be easily integrated into Shiny apps using almost the same pattern. For example, you can turn a static table in a Shiny app into an interactive table using the DT package:

  1. Create an interactive table using DT::datatable().
  2. Render it using DT::renderDT().
  3. Display it using DT::DTOutput().

In this exercise, you will update the app created previously, replacing the static table with an interactive table.

Deze oefening maakt deel uit van de cursus

Building Web Applications with Shiny in R

Cursus bekijken

Oefeninstructies

  • Create an interactive table output using DT with top 10 most popular names by sex and year. You can use the function top_10_names() to generate a data frame to display, and pass it to DT::datatable().
  • Display the table in the UI.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

ui <- fluidPage(
  titlePanel("What's in a Name?"),
  # Add select input named "sex" to choose between "M" and "F"
  selectInput('sex', 'Select Sex', choices = c("M", "F")),
  # Add slider input named "year" to select year between 1900 and 2010
  sliderInput('year', 'Select Year', min = 1900, max = 2010, value = 1900),
  # MODIFY CODE BELOW: Add a DT output named "table_top_10_names"
  tableOutput('table_top_10_names')
)

server <- function(input, output, session){
  top_10_names <- function(){
    babynames %>% 
      filter(sex == input$sex) %>% 
      filter(year == input$year) %>% 
      slice_max(prop, n = 10)
  }
  # MODIFY CODE BELOW: Render a DT output named "table_top_10_names"
  output$table_top_10_names <- renderTable({
    top_10_names()
  })
}

shinyApp(ui = ui, server = server)
Code bewerken en uitvoeren