案例研究:使用 R 的 Shiny 构建 Web 应用
Dean Attali
Shiny Consultant
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
if (input$continent != "All") {
data <- subset(
data,
continent == input$continent
)
}
renderTable()renderPlot()downloadHandler()reactive() 变量替代重复代码output$my_table <- renderTable({
data <- gapminder
data <- subset(
data,
lifeExp >= input$life[1] & lifeExp <= input$life[2]
)
})
my_data <- reactive({data <- gapminder data <- subset( data, lifeExp >= input$life[1] & lifeExp <= input$life[2] )})output$my_table <- renderTable({ my_data() })
output$table <- renderTable({
fit_model(input$num)
})
output$plot <- renderPlot({
ggplot(
fit_model(input$num), ...)
})
fit_model() 需 5 秒fit_model() 两次 = 10 秒x <- reactive({ fit_model(input$num) })output$table <- renderTable({ x() })output$plot <- renderPlot({ ggplot(x(), ...) })
x() 调用两次,但 x 内部代码只运行一次fit_model() 仅调用一次 = 5 秒惰性变量 = 仅在需要值时才计算
x <- reactive({
fit_model(input$num)
})
output$download <- downloadHandler(
filename = "x.csv",
content = function(file) {
write.csv(x(), file)
}
)
只有在请求下载时才运行 x(),而不是每次 input$num 变化
案例研究:使用 R 的 Shiny 构建 Web 应用