4 App 2: Reactives

So we’ve connected our control up. Great! Now let’s add a numeric filter to our data by using an reactive. reactives are the heart and soul of shiny. We’ll use a reactive to filter our data, and pass this filtered data on to our two plots. This means we can dynamically filter our data and our plots will update.

A reactive can be thought of a bit of code that runs whenever the controls that map to it are changed. In this case, our reactive represents our filtered dataset when we adjust our slider.

Basic workflow of reactives

Basic workflow of reactives

4.1 Exercise

  1. Open up the 02_reactives folder and the app.R file within.

  2. Try running the app. You can see that we added a slider (using sliderInput) in ui, but it doesn’t do anything. We’re going to connect that slider to filter the biopics dataset.

  3. You might notice that there is a new object in the server code, called biopics_filtered. This is where we’re going to connect our slider.

  4. Paste the following bit of code into the reactive, after biopics. What does it do?

%>% filter(year_release > input$year_filter)
  1. Notice how we call the reactive in output$scatter_plot? We have to use biopics_filtered() rather than biopics_filtered. A reactive is actually a function, and so you need to use the function notation to invoke it in a renderPlot statement.

  2. Ok, run the app again and adjust the slider. Notice how the plot axes changes. Congrats, that’s your first use of a reactive!

4.2 For More Info

We’ve only shown one type of reactive, basically a reactive data.frame. Almost any type of object can be a reactive. Here are more resources on learning about them.