让表格可交互
与内置表格相比,DT 包提供的 datatable 往往更适合在 Shiny 应用中展示数据。把 Shiny 表格转换为 datatable 只需要两处简单修改:将 tableOutput() 和 renderTable() 分别替换为 DT::dataTableOutput() 和 DT::renderDataTable()。datatable 支持丰富的自定义选项,但本练习不会使用任何特殊选项。
注意:关于 DT 包,通常的约定是不要加载 DT 包本身,而是在调用 datatable 函数时使用 DT:: 前缀。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
这里提供了上一个编码练习中的 Shiny 应用代码,未作任何修改。您的任务是将基础的 Shiny 表格替换为 DT 表格。具体要求:
- 在 UI 中,将表格输出函数替换为
DT的 datatable 输出(第 11 行)。 - 在 server 中,将表格渲染函数替换为
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)