MulaiMulai sekarang secara gratis

Choose the data source (ui)

Over the last few exercises, you've used 3 different sources for the word cloud: the Art of War book, a text field, and a text file. However, only one source was working at any given time. In this exercise, you will provide the user with a way to select which data source to use for the word cloud.

Latihan ini adalah bagian dari kursus

Case Studies: Building Web Applications with Shiny in R

Lihat Kursus

Petunjuk latihan

Your task is to add radio buttons to the app that will let the user select whether the word source should be the Art of War book, the textarea, or an uploaded file. Specifically:

  • Add a radio buttons input with a label of "Word source" that has three choices:
    • The values of the choices should be "book", "own", and "file". The names displayed to the user should be "Art of War", "Use your own words", and "Upload a file", respectively.

Latihan interaktif praktis

Cobalah latihan ini dengan menyelesaikan kode contoh berikut.

ui <- fluidPage(
  h1("Word Cloud"),
  sidebarLayout(
    sidebarPanel(
      # Add radio buttons input
      ___(
        inputId = "source",
        label = ___,
        choices = c(
          # First choice is "book", with "Art of War" displaying
          "Art of War" = "book",
          # Second choice is "own", with "Use your own words" displaying
          ___ = "own",
          # Third choice is "file", with "Upload a file" displaying
          ___ = ___
        )
      ),
      textAreaInput("text", "Enter text", rows = 7),
      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) {
  input_file <- reactive({
    if (is.null(input$file)) {
      return("")
    }
    readLines(input$file$datapath)
  })

  output$cloud <- renderWordcloud2({
    create_wordcloud(input_file(), num_words = input$num,
                     background = input$col)
  })
}

shinyApp(ui = ui, server = server)
Edit dan Jalankan Kode