Course Description Shiny is an R package that makes it easy to build highly interactive web apps directly in R. Using Shiny, data scientists can create interactive web apps that allow your team to dive in and explore your data as dashboards or visualizations. If you want to bring your data to life, Shiny is the way to go! Using data about baby names, food ingredients, and UFO sightings, you’ll build a variety of different Shiny apps that leverage different inputs and outputs. You’ll also learn the basics of reactive expressions. By the end of this course, you’ll have the Shiny skills you need to build your first app in R.

1. Get Started with Shiny

To kick off the course you’ll learn what a web app is and when you should build one, plus build a few apps of your own! You’ll first learn to make text inputs and outputs in a few ways, including exploring the popularity of certain names over time.

1.1 Introducción a Shiny

  1. Introduction to Shiny
    Welcome to “Building Web Applications in R with Shiny”. I’m Ramnath Vaidyanathan, VP of Product Research at DataCamp, and will be one of your instructors. In this course, you will learn how to turn your R code and data analyses into awesome web applications using Shiny.

  2. Introduction to Shiny
    Shiny is an R package that allows you to turn your analyses into interactive and engaging web applications without leaving the comfort of R! By the end of this course, you will be able to build real-world Shiny apps, like this one, a simple app that allows the user to interactively visualize a histogram of waiting times of the hot spring Old Faithful by changing the number of bins. You can write this app in less than 10 lines of code.

  1. What is a web app?
    It is important to understand what a web application is. These days, almost everything you encounter on the internet is a web application. All web applications have a user interface that you can interact with. Based on those interactions, the app updates the display in the server to provide you with relevant information and plots. Here are two examples.

  1. What is a web app?
    The first is from the New York Times and helps users visualize the impact of different election results on the outcome. It’s one of my all-time favorite web visualizations.

  1. What is a web app?
    The second is the DataCamp mobile app. You are presented with a practice question and a series of choices, from which you need to select the correct one. The app checks then your answer and provides appropriate feedback.

  1. How does a web app work?
    Most web apps have two parts: A client or user-interface that users interact with, and a server or backend that carries out computations or searches based on the user interactions. For example, when you use tax software to file your taxes, the user interface is where you enter information from your W2 and other tax forms. Based on the values you enter, the server calculates your tax liabilities and updates the refund amount displayed to you.

  1. What is Shiny?
    Shiny is an R package that allows you to write web applications with R. The client (user-interface) as well as the server (backend logic) are written using R code. You might ask me: “I’m a data scientist, not a web developer. Why should I build a fancy web application? Why can’t I have a web developer build it?” Let me try to convince you to do it yourself with an example scenario.

  1. Why should data scientists build web apps?
    Suppose you’ve been asked to run a cluster analysis on the iris dataset. Your finished product is a plot of clusters visualized as a scatterplot. Your manager tells you: “This is interesting, but have you considered four clusters? Or two? Can I see how the clusters look for a different set of X and Y axes?”

  1. Why should data scientists build web apps?
    You might have already anticipated some of these questions and turned your code into a function where you plug in the number of clusters, plus the x and y variables as parameters. Now, you can tell your manager: “No problem! Give me 15 minutes.” Though an improvement, creating multiple plots with this function is a far cry from the exciting work you did to cluster the data in the first place.

  1. Why should data scientists build web apps?
    With only a small amount more Shiny code, you can turn your function into a web-application that lets your manager interactively update the parameters and explore the results of the analysis himself or herself.

  1. Why should data scientists build web apps?
    This is why you should learn to build web-apps! Shiny not only helps you create web-apps, it helps you build apps that are visually gorgeous.

1.1.1 Cliente vs servidor

Most web application consist of two parts. The client contains the user interface, that is, buttons and selectors and text boxes and other things that the user can interact with. The server (or backend) is where computation happens, including things like manipulating data and running models.

Shown on the right is a web application that estimates your blood alcohol concentration (BAC) based on both your physical characteristics and the number of drinks you have had. Play around with the application!

When you are ready, identify the action that takes place on the server side.


- Note: Plotting the BAC requires estimating it first, and then generating the plot. This is indeed done on the server side.

1.1.2 ¿Cuándo crear una aplicación web?

It can be beneficial for a data scientist to turn their analyses into a web application, especially when interactive exploration of the results are useful. It is important to be able to recognize when building an app is an appropriate solution and when it might not be.

In this exercise, you will be presented with a set of scenarios. Classify each as a situation where it might be beneficial to build a web app and when it might not be.


1.2 Crea una aplicación brillante de “Hola, mundo”

  1. Build a “Hello, world” Shiny app
    I’m Kaelen Medeiros, the other instructor for this course. Now that you know what Shiny is and when to build an app, let’s build your first app. We’ll make a “Hello, world” app that begins to demonstrate the building blocks of Shiny apps.

  2. Parts of a Shiny app
    As Ramnath explained in the last lesson, an app needs a user interface, or UI, and a server. The magic of the Shiny package is that can create both of those using R code, plus run your app using an additional Shiny function. First, you’ll always have to load Shiny using the library function, as with any R package. Creating the UI doesn’t require a specialized Shiny function. Most people use fluidPage, which allows for implementation of a blank HTML fluid page layout, organized by rows and columns, for your app. The server is created in R by defining a custom function. There are other courses that teach you how to do that in more detail, but to build a server you just need the basics. Create an object called server, and then assigned to it should be a function with, at minimum, the arguments input and output, though there are optional arguments that help you create more advanced apps. In this course, we’ll also pass the session argument to specify the specific session. Finally, run the app using the shinyApp function. You’ll have to pass in your UI and server objects, usually just called ui and server, as arguments.

  1. Hello, world!!! Though not terribly interesting, here’s an example of a “Hello, world” Shiny app. Notice that all that’s been added to the basic app skeleton is the character string “Hello, world!!!” in the UI, while the server is still empty. Given that the only addition to the app is in the UI, what do you think might happen? If you guessed that this app will display the “Hello, world!!!” character string, you’re right!

  1. Ask a question (with an input!)
    Our “Hello, world” app wasn’t really that exciting. What if we could take in a name from the user, and use that name to wish that person “hello”, or to ask them a question? Shiny provides a function, textInput, that makes that possible. It allows users to enter text, and takes three arguments: a unique id that will be used to refer to this input, a label that is displayed to the user, and an optional default value, which we haven’t used in this app. Shiny actually provides a variety of functions to accept many different kinds of users inputs, which you’ll see more of throughout the course. Our full output, the question itself, is built in the server using the renderText function, and is assigned to an output object, output\(q. Inside of that, you can use paste to create a longer character string, and if you add input\)name, you can access the name added using textInput. Back up in the UI, use the textOutput function to display the output q. Voila, an app that takes and uses one input! As the course progresses, we’ll build apps that use more than one input. For the record, I like both cats and dogs, though I have a cat.

1.2.1 Crea una aplicación brillante de “Hola, mundo” (2)

Though this app doesn’t actually do anything other than display the text “Hello, world!!!”, you should get used to loading shiny and using the appropriate functions to create the UI, server, and actually run the app.

If the app were run in RStudio, it would look like:

For this exercise, make sure you create the UI before the server. You can do them in any order when building your own apps later, but for this course we’ll write them in that order.


- Note: You should load shiny, create the UI, then the server, then run shinyApp() so the app would run.

1.2.2 Entrada de la aplicación “Hello, World” (IU)

The “Hello, World!!!” app, while enthusiastic, could be more fun. Extend the app and have it wish a hello to a specific person. A user will enter a name and the app will update to wish that name “Hello”.

For users to enter text, you’ll have to use a text-specific shiny input function to capture it. Recall that shiny makes available a number of input functions depending on what kind of input you’d like to capture from your users.

shiny has been pre-loaded for you.


-Note: textInput() is the way to capture what it says - text input from your user - but there’s a lot of other kinds of input functions provided in shiny that will let you capture other types. Right now, the name isn’t going anywhere or showing up in the app. In the next exercise, you’ll work to wire up the app to display ‘Hello’ and the name entered.

1.2.3 Salida de la aplicación “Hello, World” (interfaz de usuario / servidor)

To finish up your “Hello, world” app, you’ll have to actually display the text that’s input.

Recall this is how you construct an output from an input:

shiny has been pre-loaded for you. By the end of this exercise, your app should look like this:

If you get an error message resembling Parsing error in script.R:4:3: unexpected symbol, it is very likely that you have forgotten to use a comma to separate the arguments to one of the functions.


. Server: Create an output named ‘greeting’ that displays “Hello, Kaelen” when Kaelen is input as the name. . UI:: Display the output in the UI. Be sure to add a comma after textInput(), before adding more code.

1_2_3 Salida de codigo anterior

- Note: You’ve now built your first Shiny app! This is a ‘toy’ app, or one that it’s unlikely you’d ever build in your work as a data scientist, but hopefully you’re beginning to understand the parts of an app and the principles behind Shiny. Let’s move on to a more complicated app.

1.3 Crea una aplicación brillante explorador de nombres de bebé

  1. Build a babynames explorer Shiny app
    There are many ways to build a Shiny app. Throughout this course we will follow a standard process that has worked really well for us. By the end of this lesson, you will build a Shiny app which will allow a user explore the popularity of a name over time.

  2. Sketch your app
    While building any app, it is critical to begin with the end in mind. Start by sketching how the final app will look and how the user will interact with it. From experience, I can tell you that this makes development much easier. For this app, we want to display a text box for typing a name and respond with a plot of popularity of the name over time. We’ll keep the layout simple and use a two-column layout with the text box on the left and the plot on the right, plus a title on the top.

  1. Add inputs (UI)
    Recall that every Shiny app has two components: a user interface (UI) and a server. We will start by building the user interface. First, we will add a titlePanel at the top, to display a nicely styled header. Next, we will add a textInput to let the user enter their name. We will leave the server function empty for now. To run the app, call shinyApp with the ui and server as arguments. Right now, the app only lets the user type a name. Let’s see what else we can add.

  1. Add outputs (UI/server)
    The next step is adding outputs. Our only output will be an empty plot created using ggplot2. We can add this output in two steps. First, render the output in the server using renderPlot and assign it to the output list as an element named trend. If you run the app now, you will notice that nothing has changed. There is no plot. Why? Well, we haven’t done the second step! The plot does not appear because the user interfaace has no knowledge of it. To let the UI know that there is a plot object named trend that needs to be displayed, we can use the plotOutput function and pass it the name of the output.

  1. Add outputs (UI/server)
    Running the app now, we see a text input and a plot output in a single column. In our original sketch of the app, we wanted the text to appear on the left and the plot on the right.

  1. Update layout (UI)
    We can place elements in the UI using layout functions. We will place the textInput inside sidebarPanel and the plotOutput inside mainPanel. Additionally, we will place both of these panels inside sidebarLayout.

  1. Update layout (UI)
    If we check the updated app, we now see the two-column layout. Just one step left!

  1. Update output (server)
    Our final step is creating a line plot showing the popularity of a name input by the user using ggplot2. To do this, we first create a subset of the babynames data, keeping rows where the name matches the input. We can access the input as input dollar name. We will use geom_line to generate a line plot of prop, the proportion of births in a given year with the selected name, versus year. To display separate lines based on sex, we will set color to sex. We’ve built a baby name explorer!

1.3.1 Agregar entrada (UI)

This app will allow users to enter a baby name and visualize the popularity of that name over time.

The first step is to add a text input to the UI that will allow a user to enter their (or any other) name. Try using the optional default argument this time around.

The shiny package is pre-loaded for you.


- Note: Now you understand how to add an input to your UI. You could stop here (this could be your whole app!) but let’s instead learn how to add an output as well.

1.3.2 Agregar salida (UI / servidor)

The next step in building your app is to add an empty plot as a placeholder. Recall that in order to add a plot p assigned to an object named x to a Shiny app, you need to:

  1. Render the plot object using renderPlot({p}).
  2. Assign the rendered plot to output$x.
  3. Display the plot in the UI using plotOutput("x").

The shiny and ggplot2 packages are pre-loaded for you.


- Note: Now that you have the input you created in the last exercise plus the blank plot, your app is getting more complicated and also more useful.

1.3.3 Actualizar diseño (UI)

You can use layout functions provided by Shiny to arrange the UI elements. In this case, we want to use a sidebarLayout(), where the input is placed inside a sidebarPanel() and the output is placed inside the mainPanel(). You can use this template to update the layout of your app.

We have pre-loaded the shiny and ggplot2 packages for you. Note that p(‘hello’) returns an HTML paragraph with the text “hello”.


- Note: The layout of the app is now more aesthetically pleasing, and maybe even easier for users to navigate.

1.3.4 Actualizar salida (servidor)

You are almost there! The final step is to update the plot output to display a line plot of prop vs. year, colored by sex, for the name that was input by the user. You can use this plot template to create your plot:

Recall that a user input named foo can be accessed as input$foo in the server. We have already pre-loaded the shiny and ggplot2 packages, as well as the babynames dataset.


. Add the plotting code inside renderPlot(). Make sure to replace the hard-coded name (name == “David”) with the name that was input by the user.

- Note: This is now a complete app, and is much more informative than the app that only had the name-entering functionality. We’ll continue to build informative, streamlined apps like this throughout the course.