不要不斷地重新產生新的文字雲
這個文字雲應用程式現在有好幾個不同的輸入。修改任何一個,都會讓文字雲依照新的參數重新繪製,這正是預期的行為。
但有時候這樣也會讓人困擾。舉例來說,在文字區塊輸入內容時,文字雲會在你還沒打完前就不斷重新產生。你可以用 isolate() 來控制這點。
renderWordcloud2() 中負責產生文字雲的程式碼已被移除。你的任務是重新建立文字雲,並將它隔離,讓變更參數時不會自動觸發新的文字雲。
本練習屬於課程
案例研究:使用 R 的 Shiny 建置網頁應用程式
練習說明
- 確保整個產生文字雲的函式都有被隔離(第 54 行)。
- 使用必要的輸入與反應式變數,將參數提供給
create_wordcloud()。這個函式的參數是data、num_words和background(第 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")
),
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({
# Isolate the code to render the word cloud so that it will
# not automatically re-render on every parameter change
___({
# Render the word cloud using inputs and reactives
create_wordcloud(data = ___, num_words = ___,
background = ___)
})
})
}
shinyApp(ui = ui, server = server)