Nghiên cứu tình huống: Xây dựng ứng dụng web với Shiny trong R
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() thay cho trùng lặp mã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() mất 5sfit_model() hai lần = 10sx <- reactive({ fit_model(input$num) })output$table <- renderTable({ x() })output$plot <- renderPlot({ ggplot(x(), ...) })
x() hai lần, mã trong x chỉ chạy một lầnfit_model() gọi một lần = 5sBiến lười = chỉ tính khi cần giá trị
x <- reactive({
fit_model(input$num)
})
output$download <- downloadHandler(
filename = "x.csv",
content = function(file) {
write.csv(x(), file)
}
)
x() chỉ chạy khi tải xuống được yêu cầu, không phải mỗi lần input$num đổi
Nghiên cứu tình huống: Xây dựng ứng dụng web với Shiny trong R