Modify data once with user input for multiple outputs Shiny

Hi ,

I'm working on understanding shiny better, and I've hit a problem that I can't quite figure out with reactivity. I'd like to allow users to apply filters to a dataset, then show a plot and a summary table of that dataset. However, I can't figure out how to setup the server code to only do the filtering once. Right now I have it implemented to filter twice, once in each of the output functions. Obviously this is inefficient and will be very bug prone, especially as the number of outputs figures increases. Additionally, if I am doing a random sample, I don't get the same sample in each of the output elements with this approach. How do I create a reactive data set that will update with the user input to go into all the output elements?

I'd be extra appreciative if someone could point me to the right piece of documentation for this.

Here is a simple example

library(shiny)
library(tidyverse)

# Define UI for application that draws a histogram
ui <- fluidPage(

    # Application title
    titlePanel("Old Faithful Geyser Data"),

    # Sidebar with a slider input for number of bins 
    sidebarLayout(
        sidebarPanel(
            sliderInput("sample",
                        "sample fraction:",
                        min = 0,
                        max = 1,
                        value = .5)
        ),

        # Show a plot of the generated distribution
        mainPanel(
           plotOutput("distPlot"),
           tableOutput("distTable")
        )
    )
)

# Define server logic required to draw a histogram
server <- function(input, output) {

    output$distPlot <- renderPlot({
        x    <- sample_frac(faithful, input$sample) 
        
        hist(x[,2], col = 'darkgray', border = 'white')
    })
    
    output$distTable <- renderTable({
        x    <- sample_frac(faithful, input$sample) 
        
        summary(x)
    })
}

# Run the application 
shinyApp(ui = ui, server = server)

I don't want to be repeating x <- sample_frac(faithful, input$sample)


# Define server logic required to draw a histogram
server <- function(input, output) {
  
  my_filtered_data <- reactive({
    sample_frac(faithful, input$sample) 
  })
  
  output$distPlot <- renderPlot({
    x    <- req(my_filtered_data())
    
    hist(x[,2], col = 'darkgray', border = 'white')
  })
  
  output$distTable <- renderTable({
    x   <- req(my_filtered_data())
    
    summary(x)
  })
}

https://shiny.rstudio.com/articles/reactivity-overview.html

Thank you, I had been trying to use reactive but missed that subsequent calls to the reactive expression needed to include parens. I was calling my_filtered_data instead of my_filtered_data()

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.