แสดงหรือซ่อน input ตามเงื่อนไข
แอป word cloud ตอนนี้มีวิธีป้อนคำเข้า word cloud อยู่ 3 แบบ โดย 2 แบบมี UI element เฉพาะที่ใช้งานได้กับวิธีนั้นเท่านั้น ได้แก่ textarea ที่ใช้เฉพาะเมื่อผู้ใช้เลือกแหล่งคำแบบ "own" และ file input ที่เกี่ยวข้องเฉพาะเมื่อเลือกแหล่งคำแบบ "file" ในอุดมคติแล้ว ควรแสดงเฉพาะ input ที่จำเป็นในแต่ละช่วงเวลาเท่านั้น
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
กรณีศึกษา: การสร้างเว็บแอปพลิเคชันด้วย Shiny ใน R
คำแนะนำการฝึกหัด
ขณะนี้ textarea ถูกครอบด้วย conditionalPanel() แล้ว เพื่อให้แสดงเฉพาะเมื่อผู้ใช้เลือกป้อนข้อความเอง งานของคุณคือทำให้ file input แสดงเฉพาะเมื่อผู้ใช้เลือกอัปโหลดไฟล์เป็นแหล่งข้อมูล โดยเฉพาะ:
- ครอบ file input ด้วย conditional panel (บรรทัดที่ 19)
- เงื่อนไขของ panel ต้องเป็นจริงเมื่อผู้ใช้เลือกตัวเลือก "file" จาก radio buttons ของแหล่งข้อมูล (บรรทัดที่ 22)
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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"
)
),
conditionalPanel(
condition = "input.source == 'own'",
textAreaInput("text", "Enter text", rows = 7)
),
# Wrap the file input in a conditional panel
___(
# The condition should be that the user selects
# "file" from the radio buttons
condition = ___,
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) {
data_source <- reactive({
if (input$source == "book") {
data <- artofwar
} else if (input$source == "own") {
data <- input$text
} else if (input$source == "file") {
data <- input_file()
}
return(data)
})
input_file <- reactive({
if (is.null(input$file)) {
return("")
}
readLines(input$file$datapath)
})
output$cloud <- renderWordcloud2({
create_wordcloud(data_source(), num_words = input$num,
background = input$col)
})
}
shinyApp(ui = ui, server = server)