Thêm một biểu thức reactive khác
Một biểu thức reactive có thể gọi các biểu thức reactive khác. Điều này giúp bạn mô-đun hóa các phép tính và đảm bảo chúng KHÔNG bị thực thi lặp lại. Thành thạo cách dùng các biểu thức reactive là chìa khóa để xây dựng ứng dụng Shiny hiệu năng cao.
Trong bài tập này, bạn sẽ dùng một biểu thức reactive để tính trạng thái sức khỏe dựa trên BMI.
Bài tập này là một phần của khóa học
Xây dựng ứng dụng web với Shiny trong R
Hướng dẫn bài tập
- Thêm một biểu thức reactive
rval_bmi_statusđể tính trạng thái BMI. - Dùng biểu thức reactive này để thay thế phần tính trạng thái BMI trong đầu ra.
Bài tập tương tác thực hành trực tiếp
Hãy thử làm bài tập này bằng cách hoàn thành đoạn mã mẫu này.
ui <- fluidPage(
titlePanel('BMI Calculator'),
sidebarLayout(
sidebarPanel(
numericInput('height', 'Enter your height in meters', 1.5, 1, 2),
numericInput('weight', 'Enter your weight in Kilograms', 60, 45, 120)
),
mainPanel(
textOutput("bmi"),
textOutput("bmi_status")
)
)
)
server <- function(input, output, session) {
rval_bmi <- reactive({
input$weight/(input$height^2)
})
# CODE BELOW: Add a reactive expression rval_bmi_status to
# return health status as underweight etc. based on inputs
output$bmi <- renderText({
bmi <- rval_bmi()
paste("Your BMI is", round(bmi, 1))
})
output$bmi_status <- renderText({
# MODIFY CODE BELOW: Replace right-hand-side with
# reactive expression rval_bmi_status
bmi_status <- cut(rval_bmi(),
breaks = c(0, 18.5, 24.9, 29.9, 40),
labels = c('underweight', 'healthy', 'overweight', 'obese')
)
paste("You are", bmi_status)
})
}
shinyApp(ui = ui, server = server)