Case Studies: Building Web Applications with Shiny in 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() variables instead of code duplicationoutput$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() takes 5sfit_model() called twice = 10sx <- reactive({ fit_model(input$num) })output$table <- renderTable({ x() })output$plot <- renderPlot({ ggplot(x(), ...) })
x() called twice, code inside x runs oncefit_model() called once = 5sLazy variable = not calculated until value is needed
x <- reactive({
fit_model(input$num)
})
output$download <- downloadHandler(
filename = "x.csv",
content = function(file) {
write.csv(x(), file)
}
)
x() only runs when download is requested, not every time input$num changes
Case Studies: Building Web Applications with Shiny in R