MulaiMulai sekarang secara gratis

Buat word cloud baru sesuai permintaan

Setelah mengisolasi kode render word cloud agar tidak terlalu sering diperbarui, langkah terakhir adalah menyediakan cara untuk merender word cloud hanya ketika pengguna memilih untuk melakukannya. Ini dapat dicapai dengan bantuan actionButton().

Latihan ini adalah bagian dari kursus

Studi Kasus: Membangun Aplikasi Web dengan Shiny di R

Lihat Kursus

Petunjuk latihan

Tugas Anda adalah menambahkan tombol ke aplikasi Shiny, dan merender ulang word cloud ketika tombol ditekan. Secara khusus:

  • Tambahkan action button ke aplikasi dengan input ID "draw" dan label "Draw!" (baris 26).
  • Tambahkan tombol tersebut sebagai dependensi dalam fungsi rendering word cloud sehingga word cloud akan dijalankan ulang ketika tombol ditekan (baris 56).

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

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)
Edit dan Jalankan Kode