Skip to content
R for the Rest of Us Logo

Interactive Dashboards with Shiny

Some hints on using reactives

Transcript

Click on the transcript to go to that point in the video. Please note that transcripts are auto generated and may contain minor inaccuracies.

Your Turn

The reactives/03_assignment/app.R files contains a couple of mistakes: One is storing the reactive, and the other mistake is calling the reactive. Your job is to fix the code in the apps. Confirm your app runs after you've fixed it.

Have any questions? Put them below and we will help you out!

You need to be signed-in to comment on this post. Login.

Yuri Zharikov

Yuri Zharikov • September 18, 2024

I am looking for combining two inputs into one output, e.g. in this example year as a slider and country as a drop down menu. Will this be later in the course or could you please give a hint (or refer to a source). Thank you.

Luis Francisco Gomez Lopez

Luis Francisco Gomez Lopez • December 28, 2024

Pending approval
# Libraries ----
library(shiny)
library(fivethirtyeight)
library(ggplot2)

# Choices ----
select_choices <- c("country",
                    "type_of_subject",
                    "subject_race",
                    "subject_sex")

year_min <- min(biopics$year_release, 
                na.rm = TRUE)
year_max <- max(biopics$year_release, 
                na.rm = TRUE)

# Shinny app architecture ----

## User interface object ----
ui <- fluidPage(
 
 plotOutput(outputId = "movie_plot"),
 
 sliderInput(inputId = "year_filter", 
             label = "Select Highest Year", 
             min = year_min, 
             max = year_max, 
             value = year_max),
 
 selectInput(inputId = "color_select", 
             choices = select_choices, 
             label = "Select Variable")
 
)

## Server function ----
server <- function(input, output) {
 
 # This is a function
 biopics_filtered <- reactive(x = {
  
  req(input$year_filter)
  
  biopics |> 
   filter(year_release <= input$year_filter)
  
 })
 
 # Render a reactive plot 
 ## movie_plot: id of the output
 output$movie_plot <- renderPlot(
  expr = {
            # Remember that this is a function
            ## You need
    data <- biopics_filtered()
    
    data |>
     ggplot(aes(x = year_release,
               y = box_office)) +
     geom_point(aes(color = .data[[input$color_select]]))
    
  }
)
 
}

## Callout shinyApp function
shinyApp(ui = ui, server = server)
Ted Laderas

Ted Laderas • September 19, 2024

Hi Yuri,

You can combine multiple inputs in a reactive. Here I'm using two filter statements with two different inputs:

output$biopics_filtered <- reactive({ req(input$year_slider) req(input$country) biopics |> dplyr::filter(year_release < input$year_slider) |> dplyr::filter(country == input$country) })

You can use as many inputs in a reactive as you like. Hope that answers your question.