LoslegenKostenlos loslegen

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.

Diese Übung ist Teil des Kurses

Building Web Applications with Shiny in R

Kurs anzeigen

Anleitung zur Übung

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

Interaktive Übung

Versuche dich an dieser Übung, indem du diesen Beispielcode vervollständigst.

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)
Code bearbeiten und ausführen