LoslegenKostenlos loslegen

Erzeuge bei Bedarf eine neue Wordcloud

Nachdem du den Render-Code der Wordcloud isoliert hast, damit er nicht zu häufig aktualisiert, besteht der letzte Schritt darin, die Wordcloud nur dann zu rendern, wenn der/die Nutzer:in es auswählt. Das lässt sich mit einem actionButton() erreichen.

Diese Übung ist Teil des Kurses

Fallstudien: Webanwendungen mit Shiny in R erstellen

Kurs anzeigen

Anleitung zur Übung

Deine Aufgabe ist es, der Shiny-App einen Button hinzuzufügen und die Wordcloud neu zu rendern, sobald der Button gedrückt wird. Konkret:

  • Füge der App einen Action-Button mit der Input-ID "draw" und dem Label "Draw!" hinzu (Zeile 26).
  • Füge den Button als Abhängigkeit in die Render-Funktion der Wordcloud ein, damit sie erneut ausgeführt wird, wenn der Button gedrückt wird (Zeile 56).

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