Get startedGet started for free

Choose the data source (server)

When working with radio buttons, sometimes you need to use conditional logic (if-else statements) when accessing the radio button's value in the server. This is necessary when different actions are performed depending on the exact choice, and the chosen value needs to be inspected before deciding how to proceed.

For example, with the radio buttons that select a data source, different code will need to run depending on which choice is selected.

Your next task is to use the appropriate data source in the word cloud function, according to what radio button the user chooses.

This exercise is part of the course

Case Studies: Building Web Applications with Shiny in R

View Course

Exercise instructions

  • Define a reactive variable named data_source to hold the data that will be used for the word cloud (line 28).
  • If the "book" option ("Art of War") is selected, assign the artofwar book as the data source. If the "own" option ("Use your own words") is selected, assign the textarea's value as the data source. If the "file" option ("Upload a file") is selected, assign the text from a user-submitted file as the data source (lines 33 through 36).
  • Use the data_source() reactive variable as the data argument to the word cloud function (line 51).

Hands-on interactive exercise

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

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"
        )
      ),
      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) {
  # Create a "data_source" reactive variable
  data_source <- ___({
    # Return the appropriate data source depending on
    # the chosen radio button
    if (input$source == "book") {
      data <- artofwar
    } else if (input$source == ___) {
      data <- input$___
    } else if (___ == "file") {
      data <- input_file()
    }
    return(data)
  })

  input_file <- reactive({
    if (is.null(input$file)) {
      return("")
    }
    readLines(input$file$datapath)
  })

  output$cloud <- renderWordcloud2({
    # Use the data_source reactive variable as the data
    # in the word cloud function
    create_wordcloud(data = ___(), num_words = input$num,
                     background = input$col)
  })
}

shinyApp(ui = ui, server = server)
Edit and Run Code