開始使用免費開始

加入選擇式輸入

在 shiny 應用程式中加入輸入分成兩個步驟:先在 UI 加上一個 ___Input("x") 函式,接著在伺服端用 input$x 來存取其數值。

例如,若你想讓使用者從清單中選擇一種動物,可以使用 selectInput,並用 input$animal 來參考所選的值:

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

在這個練習中,你會建立一個 Shiny 應用程式,讓使用者透過選擇性別來視覺化各性別最熱門的前 10 個名字。

本練習屬於課程

使用 R 的 Shiny 建立網頁應用程式

檢視課程

練習說明

  • 加入一個名為「sex」的選擇式輸入,讓使用者在「M」與「F」之間選擇, 預設為「F」。
  • 更新伺服端程式碼,依據所選性別取得前 10 個名字, 而不是只固定使用「F」。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

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)
編輯並執行程式碼