讓表格可互動
相較於 Shiny 內建的表格,DT 套件提供的 Datatables 通常更適合在 Shiny 應用程式中呈現資料。只要兩個簡單的程式碼調整,就能把 Shiny 表格轉成 Datatables:把 tableOutput() 與 renderTable() 分別改為 DT::dataTableOutput() 與 DT::renderDataTable()。Datatables 具備各式各樣的自訂選項,但這裡不會使用任何特別的設定。
注意:在使用 DT 套件時,慣例上不會載入 DT 套件本身,而是於呼叫相關函式時加上 DT:: 前綴。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
這裡提供上一個程式練習中的 Shiny 應用程式原始碼,尚未做任何修改。你的任務是把基本的 Shiny 表格改成 DT 表格。具體來說:
- 在 UI 中,將表格輸出函式改成
DT的 datatable 輸出(第 11 行)。 - 在 server 中,將表格繪製(render)函式改成
DT的 datatable 繪製函式(第 31 行)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
ui <- fluidPage(
h1("Gapminder"),
sliderInput(inputId = "life", label = "Life expectancy",
min = 0, max = 120,
value = c(30, 50)),
selectInput("continent", "Continent",
choices = c("All", levels(gapminder$continent))),
downloadButton("download_data"),
plotOutput("plot"),
# Replace the tableOutput() with DT's version
tableOutput("table")
)
server <- function(input, output) {
filtered_data <- reactive({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
# Replace the renderTable() with DT's version
output$table <- renderTable({
data <- filtered_data()
data
})
output$download_data <- downloadHandler(
filename = "gapminder_data.csv",
content = function(file) {
data <- filtered_data()
write.csv(data, file, row.names = FALSE)
}
)
output$plot <- renderPlot({
data <- filtered_data()
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)