始める無料で始める

年を選択するスライダー入力を追加する

スライダー入力は数値入力にとても便利です。値の範囲から選ばせたいときにも、あらかじめ用意した選択肢から静的な値を選ばせたいときにも使え、しかも selectInput() よりも表現の幅を持たせられます。

babynames に含まれる年から特定の年を選べるスライダーを追加して、その年のトップ10の名前を表示するアプリに調整しましょう。

この演習はコースの一部です

Rで作るShiny Webアプリケーション

コースを見る

演習の手順

  • ユーザーが 1900 年から 2010 年の間で年を選べるよう、名前を "year" とするスライダー入力を追加し、デフォルトを 1900 にします。
  • サーバー側のコードを更新し、1900 年固定ではなく、選択された年のトップ10の名前を取得するようにします

実践的なインタラクティブ演習

このサンプルコードを完成させて、この演習に挑戦してみましょう。

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("F", "M")),
  # CODE BELOW: Add slider input named 'year' to select years  (1900 - 2010)

  # 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 %>% 
      filter(sex == input$sex) %>% 
    # MODIFY CODE BELOW: Filter for the selected year
      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)
コードを編集して実行