Chọn nguồn dữ liệu (server)
Khi làm việc với các nút chọn (radio button), đôi khi bạn cần dùng logic điều kiện (các câu lệnh if-else) khi truy cập giá trị của radio button ở phía server. Việc này cần thiết khi các hành động khác nhau được thực hiện tùy theo lựa chọn cụ thể, và giá trị được chọn cần được kiểm tra trước khi quyết định cách xử lý tiếp theo.
Ví dụ, với các radio button để chọn nguồn dữ liệu, cần chạy những đoạn mã khác nhau tùy vào lựa chọn được chọn.
Nhiệm vụ tiếp theo của bạn là dùng đúng nguồn dữ liệu trong hàm word cloud, theo radio button mà người dùng chọn.
Bài tập này là một phần của khóa học
Nghiên cứu tình huống: Xây dựng ứng dụng web với Shiny trong R
Hướng dẫn bài tập
- Định nghĩa một biến reactive tên
data_sourceđể chứa dữ liệu sẽ dùng cho word cloud (dòng 28). - Nếu chọn tùy chọn "book" ("Art of War"), gán sách
artofwarlàm nguồn dữ liệu. Nếu chọn tùy chọn "own" ("Use your own words"), gán giá trị của ô textarea làm nguồn dữ liệu. Nếu chọn tùy chọn "file" ("Upload a file"), gán nội dung văn bản từ tệp người dùng tải lên làm nguồn dữ liệu (các dòng 33 đến 36). - Dùng biến reactive
data_source()làm đối sốdatacho hàm word cloud (dòng 51).
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(
h1("Word Cloud"),
sidebarLayout(
sidebarPanel(
radioButtons(
inputId = "source",
label = "Word source",
choices = c(
"Art of War" = "book",
"Use your own words" = "own",
"Upload a file" = "file"
)
),
textAreaInput("text", "Enter text", rows = 7),
fileInput("file", "Select a file"),
numericInput("num", "Maximum number of words",
value = 100, min = 5),
colourInput("col", "Background color", value = "white")
),
mainPanel(
wordcloud2Output("cloud")
)
)
)
server <- function(input, output) {
# Create a "data_source" reactive variable
data_source <- ___({
# Return the appropriate data source depending on
# the chosen radio button
if (input$source == "book") {
data <- artofwar
} else if (input$source == ___) {
data <- input$___
} else if (___ == "file") {
data <- input_file()
}
return(data)
})
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
output$cloud <- renderWordcloud2({
# Use the data_source reactive variable as the data
# in the word cloud function
create_wordcloud(data = ___(), num_words = input$num,
background = input$col)
})
}
shinyApp(ui = ui, server = server)