使用响应式变量减少代码重复
在前面的练习中,根据输入值筛选 gapminder 的代码重复了 3 次:一次用于表格、一次用于图形、一次用于下载处理程序。
可以使用 Reactive 变量来减少代码重复。这样通常更好,因为维护会更容易。
本练习是课程的一部分
案例研究:使用 R 的 Shiny 构建 Web 应用
练习说明
已移除用于筛选数据的重复代码块。您的任务是添加一个用于筛选数据的响应式变量,并改为使用该变量。具体来说:
- 使用
reactive()函数创建名为filtered_data的响应式变量,采用上一练习中的筛选代码(第 15 行)。 - 使用该响应式变量来渲染表格输出、图形输出以及下载文件(第 33、42 和 50 行)。
交互式实操练习
通过完成这段示例代码来试试这个练习。
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(outputId = "download_data", label = "Download"),
plotOutput("plot"),
tableOutput("table")
)
server <- function(input, output) {
# Create a reactive variable named "filtered_data"
filtered_data <- ___({
# Filter the data (copied from previous exercise)
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
data
})
output$table <- renderTable({
# Use the filtered_data variable to render the table output
data <- ___
data
})
output$download_data <- downloadHandler(
filename = "gapminder_data.csv",
content = function(file) {
# Use the filtered_data variable to create the data for
# the downloaded file
data <- ___
write.csv(data, file, row.names = FALSE)
}
)
output$plot <- renderPlot({
# Use the filtered_data variable to create the data for
# the plot
data <- ___
ggplot(data, aes(gdpPercap, lifeExp)) +
geom_point() +
scale_x_log10()
})
}
shinyApp(ui, server)