Get startedGet started for free

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.

This exercise is part of the course

Case Studies: Building Web Applications with Shiny in R

View Course

Exercise instructions

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.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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 and Run Code