Chapter 2 Your First Shiny App

Exercise 2.8.1

Create an app that greets the user by name. You don’t know all the functions you need to do this yet, so I’ve included some lines of code below. Figure out which lines you’ll use and then copy and paste them into the right place in a Shiny app.

Solution. Solution

In the UI, we will need a textInput for the user to input text, and a textOutput to output any custom text to the app. The corresponding server function to textOutput is renderText, which we can use to compose the output element we’ve named “greeting”.

Exercise 2.8.2

Suppose your friend wants to design an app that allows the user to set a number (x) between 1 and 50, and displays the result of multiplying this number by 5. This is their first attempt:

But unfortunately it has an error:


Can you help them find and correct the error?

Solution. Solution

The error here arises because on the server side we need to write input$x rather than x. By writing x, we are looking for element x which doesn’t exist in the Shiny environment; x only exists within the read-only object input.

Exercise 2.8.3

Extend the app from the previous exercise to allow the user to set the value of the multiplier, y, so that the app yields the value of x * y. The final result should look like this:

Exercise 2.8.4

Replace the UI and server components of your app from the previous exercise with the UI and server components below, run the app, and describe the app’s functionality. Then reduce the duplication in the app by using a reactive expression.

Exercise 2.8.5

The following app is very similar to one you’ve seen earlier in the chapter: you select a dataset from a package (this time we’re using the ggplot2 package) and the app prints out a summary and plot of the data. It also follows good practice and makes use of reactive expressions to avoid redundancy of code. However there are three bugs in the code provided below. Can you find and fix them?