Get startedGet started for free

Convert height from inches to centimeters

Earlier in the chapter, we practiced stopping, delaying, and triggering apps. This is a very common pattern of programming in Shiny that enables your apps to be optimized for speed (and only re-run when something is updated and your user would like to re-run the app.)

In this exercise, you'll practice some of those concepts again, just to make sure you truly understand them. Instead of calculating BMI, this app converts height in inches to centimeters.

This exercise is part of the course

Building Web Applications with Shiny in R

View Course

Exercise instructions

  • Server: Delay the execution of calculating the height in cm until the user clicks on the 'Show height in cm' button.

Hands-on interactive exercise

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

ui <- fluidPage(
  titlePanel("Inches to Centimeters Conversion"),
  sidebarLayout(
    sidebarPanel(
      numericInput("height", "Height (in)", 60),
      actionButton("show_height_cm", "Show height in cm")
    ),
    mainPanel(
      textOutput("height_cm")
    )
  )
)

server <- function(input, output, session) {
  # MODIFY CODE BELOW: Delay the height calculation until
  # the show button is pressed
  rval_height_cm <- reactive({
    input$height * 2.54
  })
  
  output$height_cm <- renderText({
    height_cm <- rval_height_cm()
    	paste("Your height in centimeters is", height_cm, "cm")
    })
}

shinyApp(ui = ui, server = server)
Edit and Run Code