Get startedGet started for free

Reactive contexts

Reactive values are special constructs in Shiny; they are not seen anywhere else in R programming. As such, they cannot be used in just any R code, reactive values can only be accessed within a reactive context.

This is the reason why any variable that depends on a reactive value must be created using the reactive() function, otherwise you will get an error. The shiny server itself is not a reactive context, but the reactive() function, the observe() function, and all render*() functions are.

This exercise is part of the course

Case Studies: Building Web Applications with Shiny in R

View Course

Exercise instructions

You are provided with a Shiny app containing two numeric inputs, num1 and num2, and a text output. Your task is to:

  • In a reactive variable called my_sum, calculate the sum of the two numeric inputs (line 10).
  • In a reactive variable called my_average, calculate the average of the two inputs (line 14).
  • In the text output, display the calculated average using the reactive variables (line 23).

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

ui <- fluidPage(
  numericInput("num1", "Number 1", 5),
  numericInput("num2", "Number 2", 10),
  textOutput("result")
)

server <- function(input, output) {
  # Calculate the sum of the inputs
  my_sum <- reactive({
    input$num1 + ___
  })

  # Calculate the average of the inputs
  my_average <- ___({
    my_sum() / 2
  })
  
  output$result <- renderText({
    paste(
      # Print the calculated sum
      "The sum is", my_sum(),
      # Print the calculated average
      "and the average is", ___
    )
  })
}

shinyApp(ui, server)
Edit and Run Code