LoslegenKostenlos loslegen

Erzeuge nicht ständig neue Wordclouds

Die Wordcloud-App hat jetzt mehrere Eingaben, und das Ändern jeder einzelnen führt dazu, dass die Wordcloud mit den neuen Parametern neu gezeichnet wird – genau wie erwartet.

Dieses Verhalten kann aber manchmal störend sein. Zum Beispiel wird beim Tippen im Textfeld die Wordcloud immer wieder neu erzeugt, ohne abzuwarten, bis du fertig bist. Das kannst du mit isolate() steuern.

Der gesamte Code innerhalb von renderWordcloud2(), der die Wordcloud rendert, wurde entfernt. Deine Aufgabe ist es, die Wordcloud neu zu erstellen und zu isolieren, sodass das Ändern der Parameter nicht automatisch eine neue Wordcloud auslöst.

Diese Übung ist Teil des Kurses

Fallstudien: Webanwendungen mit Shiny in R erstellen

Kurs anzeigen

Anleitung zur Übung

  • Stelle sicher, dass die gesamte Funktion zur Erzeugung der Wordcloud isoliert ist (Zeile 54).
  • Übergib die Argumente an create_wordcloud() mithilfe der nötigen Eingaben und reaktiven Variablen. Die Argumente der Funktion sind data, num_words und background (Zeile 56).

Das Ergebnis kann so wirken, als wäre die App kaputt, weil du keine neue Wordcloud erstellen kannst. Das wird jedoch in einer folgenden Übung behoben.

Interaktive Übung

Vervollständige den Beispielcode, um diese Übung erfolgreich abzuschließen.

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)
Code bearbeiten und ausführen