开始使用免费开始使用

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.

本练习是课程的一部分

Building Web Applications with Shiny in R

查看课程

练习说明

  • 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.

交互式实操练习

通过完成这段示例代码来试试这个练习。

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)
编辑并运行代码