Thêm một biểu thức reactive
Một biểu thức reactive là một biểu thức R sử dụng đầu vào từ widget và trả về một giá trị. Biểu thức reactive sẽ cập nhật giá trị này bất cứ khi nào widget gốc thay đổi. Các biểu thức reactive được đánh giá lười (lazy) và có bộ nhớ đệm (cached).
Trong bài tập này, bạn sẽ đóng gói một phép tính lặp lại thành một biểu thức reactive.
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 tên là
rval_bmiđể tính BMI. - Dùng biểu thức reactive này để thay thế phép tính BMI trong cả hai đầ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_range")
)
)
)
server <- function(input, output, session) {
# CODE BELOW: Add a reactive expression rval_bmi to calculate BMI
output$bmi <- renderText({
# MODIFY CODE BELOW: Replace right-hand-side with reactive expression
bmi <- input$weight/(input$height^2)
paste("Your BMI is", round(bmi, 1))
})
output$bmi_range <- renderText({
# MODIFY CODE BELOW: Replace right-hand-side with reactive expression
bmi <- input$weight/(input$height^2)
bmi_status <- cut(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)