隨按即產生新的文字雲
你已經把產生文字雲的程式碼隔離,避免太頻繁更新。最後一步是只在使用者選擇時才重新繪製文字雲。你可以使用 actionButton() 來達成。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
你的任務是替這個 Shiny 應用程式加入一個按鈕,並在按下按鈕時重新產生文字雲。具體來說:
- 在應用程式中新增一個 action button,輸入 ID 為「draw」,標籤為「Draw!」(第 26 行)。
- 在文字雲的繪製函式中把這個按鈕設為相依項,讓按下按鈕時會重新執行產生文字雲(第 56 行)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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)
),
conditionalPanel(
condition = "input.source == 'file'",
fileInput("file", "Select a file")
),
numericInput("num", "Maximum number of words",
value = 100, min = 5),
colourInput("col", "Background color", value = "white"),
# Add a "draw" button to the app
___(inputId = ___, label = ___)
),
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({
# Add the draw button as a dependency to
# cause the word cloud to re-render on click
input$___
isolate({
create_wordcloud(data_source(), num_words = input$num,
background = input$col)
})
})
}
shinyApp(ui = ui, server = server)