依預期壽命篩選
Shiny 的真正優勢在於把輸入與輸出結合起來。上一個練習所建立的表格是靜態的——無法更動——但在探索資料時,若能讓使用者自行決定要看哪一部分的資料會更好。
你可以透過加入一個輸入元件,讓使用者選取用來篩選資料的數值,這樣就能把我們在前一個練習做的表格變成動態的。
gapminder 資料集中的其中一個變數是 lifeExp(預期壽命)。你的任務是替 Shiny 應用程式加入一個滑桿輸入,讓使用者選擇最小與最大預期壽命,表格只會顯示符合這些條件的資料。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
- 在 UI 中加入一個 ID 為「life」的滑桿輸入,最小值為 0、最大值為 120,預設選取範圍為 30–50。
- 在 render 函式內,使用輸入值將
gapminder資料篩選為只包含lifeExp介於最小與最大值(含邊界)的紀錄。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
ui <- fluidPage(
h1("Gapminder"),
# Add a slider for life expectancy filter
___(inputId = ___, label = "Life expectancy",
min = ___, max = ___,
value = c(30, 50)),
tableOutput("table")
)
server <- function(input, output) {
output$table <- renderTable({
data <- gapminder
data <- subset(
data,
# Use the life expectancy input to filter the data
lifeExp >= ___life[1] & lifeExp <= ___life[2]
)
data
})
}
shinyApp(ui, server)