Bắt đầu ngayBắt đầu miễn phí

Thêm một select input

Thêm một input vào ứng dụng shiny gồm hai bước: trước hết bạn thêm hàm ___Input("x") vào UI, sau đó truy cập giá trị của nó trong server bằng input$x.

Ví dụ, nếu bạn muốn người dùng chọn một con vật từ danh sách, bạn có thể dùng selectInput và tham chiếu giá trị đã chọn là input$animal:

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

Trong bài tập này, bạn sẽ xây dựng một ứng dụng Shiny cho phép người dùng trực quan hóa 10 tên phổ biến nhất theo giới tính bằng cách thêm một input để họ chọn giới tính.

Bài tập này là một phần của khóa học

Xây dựng ứng dụng web với Shiny trong R

Xem khóa học

Hướng dẫn bài tập

  • Thêm một select input tên "sex" để người dùng chọn giữa "M" và "F", với mặc định là "F".
  • Cập nhật mã server để lấy top 10 tên cho giới tính đã chọn thay vì chỉ "F".

Bài tập tương tác thực hành trực tiếp

Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.

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)
Chỉnh sửa và Chạy Mã