How to build a Shiny app

First, we need to install the shiny package. If you don't have it, make sure to run the following code:

install.packages("shiny")

To build a Shiny application with R, we need to construct the two structures we talked about before. The user's interface is a web page based on an HTML code, and, as the name says, it is an interface that users can interact with; it can be an interactive plot, texts, images, and so on. You don't need to worry if you don't know anything about HTML since we are going to use the shiny package to build it, though some knowledge about it can help you to build an improved app. The server, otherwise, must contain all information needed by the web server to provide the information requested by the UI. Run the following code if you want to see some examples:

library(shiny)
runExample()
runExample('01_hello')

A couple of things are happening now. A window with a histogram chart and a sidebar appeared (it is the UI), and your RStudio is still running the application (if you look at it, a Listening on http://127.0.0.1:6931 message is shown in your R console). It happens because, by creating a Shiny application, an interface is shown based on the predefined codes. In this example, when the user moves the sidebar, interacting with the app, new code lines are requested. So, the Shiny app receives and sends them to the server. The server is going to process the new information according to what it was programmed to do, generating a new interface to be shown. This happens so fast that the user may not detect the information flow. To end the application, click the red stop sign in your R console, or close the UI window.

In the previous example, the code lines needed to build that application are shown too, and, if you analyze it, you may note that they have same structure as the following code. Because of the interaction between the ui function and the server function, the shiny package requests this kind of structure. I recommend you always use the same template, it will make it easier for you to understand your application. So, open a new R script and name it as app. R and write the following code:

library(shiny)

#The UI object
ui <- fluidPage()

#The server function
server <- function(input, output) {}

#Run the app
shinyApp (ui = ui, server = server)
The name of your app R script must be app.R. Otherwise, the shiny package won't recognize it as an application, and you will have trouble running your code. So, every time you need to create a new app, you will also need to open a new R directory and save a new app.R file inside it. If you want, you can create two R scripts, one for the ui function and another for the server function, but you must name them as ui.R and server.R respectively, remembering to keep them in the same directory.

If you run the code, a blank UI window will appear. This is the shortest kind of application that you can build. The ui object is where all of the elements needed to create the UI are stored and, hence, it contains what is going to be shown to the users. So, things like the web page name and the desired  input and output are defined here. The fluidPage function is necessary to create the fluid page layouts; you can try ?fluidPage in your console to learn more about it, but basically it is where you create the structure of your web page, define the input and output, and add the elements. The server function that receives the input from the UI, builds the R elements according to them (it can be a plot, a table, or anything else that is possible to do with R), and assembles it as the output required by the UI. You must build your app around the input and output using the following code:

library(shiny)

#The UI object
ui <- fluidPage(numericInput(inputId = "df", label = "Numbers between 1
and 50:", value = 1, min = 1, max = 50, step = 1),
plotOutput(outputId = "norm"))

#The server function
server <- function(input, output) {}

#Run the app
shinyApp (ui = ui, server = server)

Note that a number box with the number one inside it now appears, where you can choose any natural number between 1 and 50, and a big blank space. The number box appears because of the input function inside the fluidPage function. There are many kinds of inputs, and they represent any possible interaction the user can do on a web page. You can choose one or more input function, according to your necessity. They are: actionButton()submitButton()checkboxInput()checkboxgroupInput(), dateInput()dateRangeInput(), fileInput(), numericInput(), sliderInput(), passwordInput(), radioButtons(), selectInput(), and textInput(). Inside the input function, we call the arguments required for that input to work properly. Each input has its own arguments, so type ?*Input to look for them (change the asterisk for an input function; in our example, type ?numericInput to see the arguments we wrote previously). The label argument is a textbox that will appear along with the input in our web page; use empty quotations marks if you don't want it. There is an important argument inside all of the input functions that we must talk about: inputId. It is an argument to name the respective input, and you can choose any character string nickname, but it needs to be properly specified because the server function uses it to read the user interaction.

Next, and separated with a comma, comes the output. Output is the thing you can do with R. It can be a plot, a text, an image, and so on. As the input functions, there are specific kinds of output functions according to what you want to be shown in your web page. They are: plotOutput(), tableOutput(), textOutput(), htmlOutput(), imageOutput()dataTableOutput(), uiOutput(), and verbatimTextOutput(). While output is assembled in the server function, it needs to be specified here, so the UI can keep a space for it (it is the big blank space mentioned before). In addition, we need to name it as the outputId argument, just like we did with the input. We can create as many input and output as needed, just separate them with a comma.

The output object is built in the server function, so let's talk about it now.

The server function assembles input into output. You do this by inserting a list, such as an object that must be called as output and $ plus outputId. Every time you need to refer to a specific output in the server function, use the output$output_nameId tag, where output_nameId is outputId chosen in the UI output function. The many output functions you have defined in the UI are listed here. Don't use commas to separate them; simply do it as is shown in the following but don't try to run the code, it is only an example:

server <- function(input, output) {
output$output_nameId1 <- renderFunction({})
output$output_nameId2 <- renderFunction({})
… )

Another important thing that must be specified and inserted in your code is the render function; it creates the type of output you wish to make. In the preceding example, I wrote renderFunction, but it isn't the right nomenclature. You need to choose the proper render function according to what will be displayed. The render functions are: renderPlot(), renderPrint(), renderTable(), renderText(), renderUI(), renderImage(), and renderDataTable(). Any R expression surrounded by the render function braces ({}) will be displayed in the UI, at the place specified by the output function.

So how do we create reactive objects inside the server function? The last important thing you need to know about the server function is to insert the inputs as variables inside the render functions, in the objects you desire the user to interact with. When you refer to the inputs in the server function, it follows the same standard as the output, so use input$input_nameId to call them. It must have this syntax. The following example would plot a sequence between 1 and any number set by the user in the input element:

library(shiny)

#the UI object
ui <- fluidPage(numericInput(inputId = "a_number",
label = "Numbers between 1 and 50:",
value = 1, min = 1, max = 50, step = 1),
plotOutput(outputId = "a_plot"))

#the server function
server <- function(input, output) {
output$a_plot <- renderPlot({plot(seq(0,input$a_number))})
}

#Run the app
shinyApp (ui = ui, server = server)

Let's get practical and build a useful app. Do you remember our plot about normal and t-distributions in Chapter 2, Descriptive and Inferential Statistics? Here is how to write an application for it:

library(shiny)

#the Users Interface
ui <- fluidPage(
titlePanel("Difference between normal and t distributions!"),
sidebarLayout(
sidebarPanel(
numericInput(inputId = "freedom",
label = "Degrees
of Freedom:",
value = 1, min = 1,
max = 50,
step = 1)),
mainPanel(plotOutput(outputId = "norm")
)
)
)

#the server function
server <- function(input, output) {
output$norm <- renderPlot({
x <- seq(-5,5,.1)
par(lwd = 2)
plot(x, dnorm(x), type = 'l', ylab = 'density',
main = 'Prob. Density Distributions')
lines(x, dt(x, input$freedom), col = '#e66101', lty = 2)
legend('topright',
legend = c('normal','t-student'),
col = c('#000000','#e66101'), lty = 1:2)
})
}
#Run the app
shinyApp (ui = ui, server = server)

Inside the fluidPage() function, the titlePanel() function was called to set the web page name. The sidebarLayout() function creates a Shiny app with a sidebar, and always needs two arguments: sidebarPanel() and mainPanel(). In the sidebarPanel function, we inserted the input, and, in mainPanel we inserted the outputs. This structure is the more common type of UI application built with the shiny package.

Yet, you can insert multiple HTML contents inside the titlePanel, sidebarPanel, or mainPanel functions, separating them with a comma if more than one is necessary. The shiny package will recognize it properly.

In the server function, I called the output$norm output, only because I named outputId as norm in the mainPanel UI output function. The renderPlot function was used to render a plot. So I just needed to write the plot code lines inside the braces of the render function. I want you to interact with the numbers of degrees of freedom, I changed the df argument inside the dt() function by the input$freedom input, as I named it with inputId on the sidebarPanel function. When you change the value in the numeric input, the Shiny app changes the plot and you can see that, the more you increase the degrees of freedom, the more the student distribution looks like the normal distribution. The following shows what the app looks like if you run the preceding code:

Figure 11.1: Probability density distributions application

It makes it much easier to view the interaction between the degrees of freedom and the t-distribution with our brand new app. So, let's learn a little more about the features required to build an app in the next section.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.107.110