IniziaInizia gratis

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.

Questo esercizio fa parte del corso

Building Web Applications with Shiny in R

Visualizza il corso

Istruzioni dell'esercizio

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

Esercizio pratico interattivo

Prova a risolvere questo esercizio completando il codice di esempio.

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)
Modifica ed esegui il codice