เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

Add a select input

Adding an input to a shiny app is a two step process, where you first add an ___Input(“x”) function to the UI and then access its value in the server using input$x.

For example, if you want users to choose an animal from a list, you can use a selectInput, and refer to the chosen value as input$animal:

selectInput(
  'animal', 
  'Select Animal', 
  selected = 'Cat', 
  choices = c('Dog', 'Cat')
)

In this exercise, you will build a Shiny app that lets users visualize the top 10 most popular names by sex by adding an input to let them choose the sex.

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Building Web Applications with Shiny in R

ดูคอร์ส

คำแนะนำการฝึกหัด

  • Add a select input named "sex" to let users choose between "M" and "F", with a default of "F".
  • Update server code to get the top 10 names for the chosen sex instead of "F" only.

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

ui <- fluidPage(
  titlePanel("What's in a Name?"),
  # CODE BELOW: Add select input named "sex" to choose between "M" and "F"

  # Add plot output to display top 10 most popular names
  plotOutput('plot_top_10_names')
)

server <- function(input, output, session){
  # Render plot of top 10 most popular names
  output$plot_top_10_names <- renderPlot({
    # Get top 10 names by sex and year
    top_10_names <- babynames %>% 
      # MODIFY CODE BELOW: Filter for the selected sex
      filter(sex == "F") %>% 
      filter(year == 1900) %>% 
      slice_max(prop, n = 10)
    # Plot top 10 names by sex and year
    ggplot(top_10_names, aes(x = name, y = prop)) +
      geom_col(fill = "#263e63")
  })
}

shinyApp(ui = ui, server = server)
แก้ไขและรันโค้ด