將身高從英吋轉換為公分
在本章前面,你已經練習過如何暫停、延遲,以及觸發應用程式。這是在 Shiny 裡非常常見的程式設計模式,能讓你的應用程式在速度上更佳(只有在某些內容更新「而且」你想要重新執行應用程式時,才會重新執行)。
在這個練習中,你會再次練習這些概念,以確保你真的掌握。這次不是計算 BMI,而是把以英吋為單位的身高轉換為公分。
本練習屬於課程
使用 R 的 Shiny 建立網頁應用程式
練習說明
- Server:將計算公分身高的執行延後,直到使用者點擊「Show height in cm」按鈕為止。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)