開始使用免費開始

加入年份篩選:數值滑桿輸入

滑桿輸入和數值輸入的用途相近,因為兩者都能讓使用者選取數字。

如果滑桿的初始值(value 參數)是一個單一數字,滑桿就會用來選取單一數值。不過,如果初始值是一個包含兩個數字的向量,滑桿就會用來選取「兩個數值」,而不是只有一個。

我們已經看過不同輸入元件可能有不同的參數。要記住每個輸入元件的確切參數並不容易。想知道某個特定輸入函式可用哪些參數,唯一的方法就是查看它的文件或說明檔。

本練習屬於課程

案例研究:使用 R 的 Shiny 建置網頁應用程式

檢視課程

練習說明

  • 在 UI 中加入一個 sliderInput(),ID 為「years」,標籤為「Years」(第 14 行)。
    • 將最小值設為資料集中最早的年份,最大值設為資料集中最新的年份。
    • 預設情況下,滑桿的端點應設為 1977 與 2002,這樣只會顯示介於這兩個年份(含)之間的資料。
  • 在 server 中加入程式碼,將輸入所選的年份用來篩選 gapminder 資料,只顯示位於這些年份範圍內的紀錄(第 28 行)。

動手互動練習

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

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      textInput("title", "Title", "GDP vs life exp"),
      numericInput("size", "Point size", 1, 1),
      checkboxInput("fit", "Add line of best fit", FALSE),
      radioButtons("color", "Point color",
                   choices = c("blue", "red", "green", "black")),
      selectInput("continents", "Continents",
                  choices = levels(gapminder$continent),
                  multiple = TRUE,
                  selected = "Europe"),
      # Add a slider selector for years to filter
      ___("years", ___, ___, ___, ___)
    ),
    mainPanel(
      plotOutput("plot")
    )
  )
)

# Define the server logic
server <- function(input, output) {
  output$plot <- renderPlot({
    # Subset the gapminder data by the chosen years
    data <- subset(gapminder,
                   continent %in% input$continents &
                   year >= ___$years[1] & year <= ___$years[2])
    
    p <- ggplot(data, aes(gdpPercap, lifeExp)) +
      geom_point(size = input$size, col = input$color) +
      scale_x_log10() +
      ggtitle(input$title)
    
    if (input$fit) {
      p <- p + geom_smooth(method = "lm")
    }
    p
  })
}

shinyApp(ui = ui, server = server)
編輯並執行程式碼