Building Shiny App exercises part 7

Connect widgets & plots

In the seventh part of our journey we are ready to connect more of the widgets we created before with our k-means plot in order to totally control its output. Of cousre we will also reform the plot itself properly in order to make it a real k-means plot.
Read the examples below to understand the logic of what we are going to do and then test yous skills with the exercise set we prepared for you. Lets begin!

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

First of all let’s move the widgets we are going to use from the sidebarPanel into the mainPanel and specifically under our plot.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Remove the textInput from your server.R file. Then place the checkboxGroupInput and the selectInput in the same row with the sliderInput. Name them “Variable X” and “Variable Y” respectively. HINT: Use fluidrow and column.

Create a reactive expression

Reactive expressions are expressions that can read reactive values and call other reactive expressions. Whenever a reactive value changes, any reactive expressions that depended on it are marked as “invalidated” and will automatically re-execute if necessary. If a reactive expression is marked as invalidated, any other reactive expressions that recently called it are also marked as invalidated. In this way, invalidations ripple through the expressions that depend on each other.
The reactive expression is activated like this: example <- reactive({ })

Exercise 2

Place a reactive expression in server.R, at any spot except inside output$All and name it “Data”. HINT: Use reactive

Connect your dataset’s variables with your widgets.

Now let’s connect your selectInput with the variables of your dataset as in the example below.

#ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Shiny App"),

sidebarLayout(
sidebarPanel(h2(“Menu”),
selectInput(‘ycol’, ‘Y Variable’, names(iris)) ),
mainPanel(h1(“Main”)
)
)
))
#server.R
shinyServer(function(input, output) {
example <- reactive({
iris[, c(input$ycol)]
})
})

Exercise 3

Put the variables of the iris dataset as inputs in your selectInput as “Variable Y” . HINT: Use names.

Exercise 4

Do the same for checkboxGroupInput and “Variable X”. HINT: Use names.

Select the fourth variabale as default like the example below.

#ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Shiny App"),

sidebarLayout(
sidebarPanel(h2(“Menu”),
checkboxGroupInput(“xcol”, “Variable X”,names(iris),
selected=names(iris)[[4]]),
selectInput(“ycol”, “Y Variable”, names(iris),
selected=names(iris)[[4]])
),
mainPanel(h1(“Main”)
)
)
))
#server.R
shinyServer(function(input, output) {
example <- reactive({
iris[, c(input$xcol,input$ycol)
]
})
})

Exercise 5

Make the second variable the default choise for both widgets. HINT: Use selected.

Now follow the example below to create a new function and place there the automated function for k means calculation.

#ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("Shiny App"),

sidebarLayout(
sidebarPanel(h2(“Menu”),
checkboxGroupInput(“xcol”, “Variable X”,names(iris),
selected=names(iris)[[4]]),
selectInput(“ycol”, “Y Variable”, names(iris),
selected=names(iris)[[4]])
),
mainPanel(h1(“Main”)
)
)
))
#server.R
shinyServer(function(input, output) {
example <- reactive({
iris[, c(input$xcol,input$ycol)
]
})
example2 <- reactive({
kmeans(example())
})
})

Exercise 6

Create the reactive function Clusters and put in there the function kmeans which will be applied on the function Data. HINT: Use reactive.

Connect your plot with the widgets.

It is time to connect your plot with the widgets.

Exercise 7

Put Data inside renderPlot as first argument replacing the data that you have chosen to be plotted until now. Moreover delete xlab and ylab.

Improve your k-means visualiztion.

You gan change automatically the colours of your clusters by copying and pasting this part of code as first argument of renderPlot before the plot function:

palette(c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3",
"#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999"))

We will choose to have up to nine clusters so we choose nine colours.

Exercise 8

Set min of your sliderInput to 1, max to 9 and value to 4 and use the palette function to give colours.

This is how you can give different colors to your clusters. To activate these colors put this part of code into your plot function.

col = Clusters()$cluster,

Exercise 9

Activate the palette function.

To make your clusters easily foundable you can fully color them by adding into plot function this:
pch = 20, cex = 3

Exercise 10

Fully color the points of your plot.




Building Shiny App exercises part 6

RENDER FUNCTIONS

In the sixth part of our series we will talk about the renderPlot and the renderUI function and then we will be ready to create our first visualization. (Find part 1-5 here).
We are going to create a simple interactive scatterplot that will help us see the clusters that are created when we run the k-means algorithm on our dataset. Read the examples below to understand how to activate a renderPlot function and the test yous skills with the exercise set we prepared for you. Lets begin!

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

DESCRIPTIVE STATISTICS

As in every statistical application it is wise to apply descriptive statistics on your dataset and also provide this information to user in an easy-readable way. So, first of all we will place a Data Table inside the “SUMMARY” tabPanel. The example below can be your guide.

#ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
dataTableOutput("Table")
)
)))

#server.R
shinyServer(function(input, output, session) {
sum<-as.data.frame.array(summary(iris))
output$Table <- renderDataTable(sum)
})

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Create a Data Table(“Table2”) with the descriptive statistics of your dataset. HINT: Use summary, as.data.frame.array and renderDataTable.

renderPlot

The renderPlot function enders a reactive plot that is suitable for assigning to an output slot. The general form of the function that generates the plot is below:

renderPlot(expr, width = "auto", height = "auto", res = 72, ...,
env = parent.frame(), quoted = FALSE, execOnResize = FALSE,
outputArgs = list())

The example below shows you how to create a simple scatterplot between two variables of the iris dataset(“Sepal Length” and “Sepal Width”).

# ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(
),
mainPanel(
plotOutput("plot1")
)
)))

#server.R
shinyServer(function(input, output, session) {
output$plot1 <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width)
})
})

Initially remove renderImage and radioButtons from the tabPanel “K means”.

Exercise 2

Add a scatterplot inside the tabPanel “K Means” between two variables of the iris dataset.

INTERACTIVE PLOTS

Shiny has built-in support for interacting with static plots generated by R’s base graphics functions,this makes it easy to add features like selecting points and regions, as well as zooming in and out of images.
To get the position of the mouse when a plot is clicked, you simply need to use the click option with the plotOutput. For example, this app will print out the x and y coordinate position of the mouse cursor when a click occurs.

#ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(),
mainPanel(
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info")
)
)))

#server.R
shinyServer(function(input, output, session) {
output$plot1 <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width)
})
output$info <- renderText({
paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
})
})

Exercise 3

Add click inside the plotOutput you just created. Name it “mouse”.

Exercise 4

Add a verbatimTextOutput inside the “K Means” tabPanel,under the plotOutput you created before. Name it “coord”.

Exercise 5

Make “x” and “y” coordinates appear in the pre-tag you just created. HINT : Use renderText and paste0 and do not forget to activate it with the submitButton.

Exercise 6

Set height = “auto” and width = “auto”.

PLOT ANNOTATION

This function can be used to add labels to a plot. Its first four principal arguments can also be used as arguments in most high-level plotting functions. They must be of type character or expression. In the latter case, quite a bit of mathematical notation is available such as sub- and superscripts, greek letters, fraction, etc.
title(main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
line = NA, outer = FALSE, ...)

Look at the example below:
# ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(),
mainPanel(
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info")
)
)))

#server.R
shinyServer(function(input, output, session) {
output$plot1 <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width,main = "SCATTER PLOT",sub = "K Means",xlab="Sepal Length",ylab = "Sepal Width")
})
output$info <- renderText({
paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
})
})

Exercise 7

Set scatterplot title to “K-Means”, the X-axis label to “Petal Length” and the Y-axis label to “Petal Width”. HINT: Use main,xlab,ylab.

You can also modify and set other graphical parameters related to the title and subtitle like the example below:

# ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel(),
mainPanel(
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info")
)
)))

#server.R
shinyServer(function(input, output, session) {
output$plot1 <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width,main = "SCATTER PLOT",sub = "K Means",xlab="Sepal Length",ylab = "Sepal Width",
cex.main = 3, font.main= 5, col.main= "green",
cex.sub = 0.65, font.sub = 4, col.sub = "orange")
})
output$info <- renderText({
paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
})
})

Exercise 8

Give values to the rest of the graphical parameters of the title like the example above and get used to them. HINT: Use cex.main, font.main and col.main.

renderUI

renderUI(expr, env = parent.frame(), quoted = FALSE, outputArgs = list())

Makes a reactive version of a function that generates HTML using the Shiny UI library. As you can see in the example below this expression returns a tag object.

# ui.R
library(shiny)
shinyUI(fluidPage(
sidebarLayout(
sidebarPanel( uiOutput("Controls")),
mainPanel(
plotOutput("plot1", click = "plot_click"),
verbatimTextOutput("info")
)
)))

#server.R
shinyServer(function(input, output, session) {
output$plot1 <- renderPlot({
plot(iris$Sepal.Length,iris$Sepal.Width,main = "SCATTER PLOT",sub = "K Means",xlab="Sepal Length",ylab = "Sepal Width",
cex.main = 2, font.main= 4, col.main= "blue",
cex.sub = 0.75, font.sub = 3, col.sub = "red")
})
output$info <- renderText({
paste0("x=", input$plot_click$x, "\ny=", input$plot_click$y)
})
output$Controls <- renderUI({
tagList(
sliderInput("n", "N", 1, 1000, 500),
textInput("label", "Label")
)
})
})

Exercise 9

Put a uiOutput inside tabPanel “K-Means” and name it “All”. Then create its output in server.R with a tagList into it. HINT: Use uiOutput, renderUI and tagList.

Exercise 10

Remove the submitButton and move the sliderInput and the textOutput from the ui.R into the tagList.




Multipanel Graphics in R (part 1)

Multipanel Graphics in RIn many situations, we require that several plots are placed in the same figure as subplots. R has various ways of doing it. Base Graphics has three different ways to draw subplots, i.e. mfrow, layout and split.screen, with increasing degree of complexity, and, at the same time, with increased control over the plot elements. This example introduces the mfrowmfcol and layout functions in Base Graphics. We use the familiar iris dataset for the illustrations.

Answers to the exercises are available here.If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Exercise 1
Consider the iris dataset, draw the following scatterplots, a) Sepal.Length vs Sepal.Width, b) Sepal.Length vs Petal.Length , and c) Sepal.Length vs Petal.Width . Annotate each scatterplot with a title. Use separate colors and plotting characters for each plot.

Exercise 2
Plot the three scatterplots in the same figure as subplots arranged in one row. Use mfrow.

Exercise 3
Plot the three scatterplots in the same figure as subplots arranged in one column. Use mfrow .

Exercise 4
Repeat the same scatterplots. Partition in such a way that the first row contains plots a and b, and the second row contain plot c. Use mfrow.

Exercise 5
Repeat Exercise 2 with mfcol.

Exercise 6
Repeat Exercise 3 with mfcol.

Exercise 7
Repeat Exercise 4 with mfcol.

Exercise 8
Repeat Exercise 2 with layout.

Exercise 9
Repeat Exercise 3 with layout.

Exercise 10
Repeat Exercise 4 with layout. In this case, let scatterplot c occupy the second row completely.




Building Shiny App Exercises (part 5)

RENDER FUNCTIONS
In the fourth part of our series we just “scratched the surface” of reactivity by analyzing some of the properties of the renderTable function.
Now it is time to get deeper and learn how to use the rest of the render functions that shiny provides. As you were told in part 4 these are:

renderImage
renderPlot
renderPrint
renderText
renderUI

Below you will see the functionality of three of them (renderImage, renderText and renderPrint) and then we will be ready to use those of them that match our needs in the next parts, just like the widgets and give a specific form to our application. As you will probably understand, when reading this part our aim is to perform several statistical analyses on our dataset. We will start by creating a K-Means tabPanel.

Follow the examples to understand the logic of the tools you are going to use and then enhance the app you started creating in part 1 by practising with the exercise set we prepared for you. Lets begin!

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

renderImage
Sending pre-rendered images with renderImage.
These are images saved as a link to a source file. If your Shiny app has pre-rendered images saved in a subdirectory, you can send them using renderImage. Suppose the images are in the subdirectory “www”/, and are named “image1.png”, “image2.png”, and so on. The following code would send the appropriate image, depending on the value of input$n:

# ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("RenderImage"),
sidebarLayout(
sidebarPanel(
radioButtons("n", label = h4("Radio Buttons"),
choices = list("Choice 1" = 1, "Choice 2" = 2),
selected = 2)
),
mainPanel(
imageOutput("Image")
)
)

))
#server.R

shinyServer(function(input, output, session) {
# Send a pre-rendered image, and don't delete the image after sending it
output$Image <- renderImage({
# When input$n is 3, filename is ./images/image3.jpeg
filename <- normalizePath(file.path('./www',
paste('image', input$n, '.png', sep='')))

# Return a list containining the filename
list(src = filename)

}, deleteFile = FALSE)
})

Now let’s break down what the code above exactly does. First of all as we saw in part 1 you should save your images in a subdirectory called “www” inside the directory that you work. Let’s say you save 2 images and you name them “image1” and “image2”. As you can see we use radioButtonshere to select which one of the two we want to be displayed. The filename contains the exact output path of the images while the list contains the filename along with some other values.
In this example, deleteFile is FALSE because we don’t want Shiny to delete an image after sending it.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Place a tabPanel in the tabsetPanel of your Shiny App. Name it “K Means”.

Exercise 2

Move the radioButtons from the sidebarPanel inside the tabPanel “K Means” you just created and name it “Select Image”. Also, move the submitButton from the sidebarPanel to the tabPanel “K Means” without title.

Exercise 3

Place an imageOutput inside the tabPanel “K Means” with name “Image” (ui.R) and the reactive function of it (server.R). Still nothing happens. HINT: Use renderImage.

Create a subdirectory inside the directory you work and name it “images”. Put there two images with names “pic1” and “pic2” respectively and .png ending.

Exercise 4

Now create the filename. Follow the example above to create the right path. Do not forget to connect it with the radioButtons. Two steps left.

Exercise 5

Now it is time to set deleteFile = “FALSE”.

Exercise 6

Create the list that contains the filename.

Exercise 7

Set width = 300 and height = 200 into the list.

renderText-renderPrint

The example below shows how the renderText works.

#ui.R
library(shiny)
shinyUI(fluidPage(
titlePanel("RenderImage"),
sidebarLayout(
sidebarPanel(
sliderInput("slider1", label = h4("Sliders"),
min =3 , max = 10, value =3)
),
mainPanel(
textOutput("text1")
)
)
))

#server.R
shinyServer(function(input, output, session) {

output$text1 <- renderText({
paste(“You have selected”, input$slider1,”clusters”)
})
})

The code above takes a numeric value from the sliderInput and puts it in the exact place of our sentence in the mainPanel.

Before proceeding to the next exercise move the sliderInput from the sidebarPanel just after the imageOutput in the tabPanel “K Means”. Then change its name to “Clusters”, its min to 3, its max to 10 and value to 3.

Exercise 8

Put the textOutpout named “text1” inside your tabPanel exactly after the sliderInput, then place its reactive function inside server.R using renderText.

Exercise 9

Display the reactive output by putting inside the renderText function the sentence “You have selected”,(?),”clusters.” HINT : Use paste.

Exercise 10

Follow exactly the same steps but this time instead of renderText use renderPrint and note the difference.




Plotly : Advanced plots and features

Plotly is a d3 based graphing library used to produce interactive and high quality graphs in R. In the following exercises, we will look at some advanced plots and features avaialable in the package. Please note that the list here is not exhaustive.
We will use datasets available in base R packages.

You are expected to have the knowledge of generating basic plots using plotly package before attempting this exercise set. It is recommended that you go through this exercise set to test your knowledge on plotly basics.

Answers to the exercises are available here.

Refer to this link for more help on the plotly functions.
For a quick info on the functions and arguments required to build basic plotly plots, refer to this cheat sheet.

Learn more about Plotly in Section 17 Interactive Visualizations with Plotly of the online course Data Science and Machine Learning Bootcamp with R.

Exercise 1

Install and load the latest version of plotly package.

Generate separate histograms for the first four columns of iris dataset and save the plots in objects p1, p2, p3 and p4.
HINT: Use plot_ly() function with x argument and type="histogram". Use name argument to give appropriate name for the trace.

Exercise 2

a. Use subplot() function to generate a plot with all the plot objects from previous exercise as the arguments.

b. Use the nrows argument to arrange 2 plots per row.

Exercise 3

a. Generate a scatter plot for the iris dataset with first column on the x-axis and second column on the y-axis. Save the plot object.

b. Generate a 2d histogram using the add_histogram2d() function.Save the plot object.
HINT: Use the function plot_ly() with the same x and y arguments and pass the plot object to the 2-d histogram function.

Exercise 4

Generate a subplot with the scatter plot and the 2-d histogram created in the previous exercise.

Notice how the scatter plot can be represented in a more interesting way. Cells in the 2-d histogram are binned and represented with the color on the scale based on the cell population/density.

Exercise 5

Set the value of shareX and shareY arguments in the subplot() function to scale the plots to the same range of x and y.

Exercise 6

Now, let us build a 3-d surface plot. The syntax to build such plot is as below.
plot_ly(z = matrix(1:100, nrow = 10)) %>% add_surface()
Click, hold and drag the cursor to see the plot surface.

Build a 3-d surface plot using the volcano dataset available in the base R distribution.

Exercise 7

Let’s look at few helpful and commonly used arguments from the layout() function.

Create and save a scatter plot object with first and second columns of iris dataset as x and y arguments respectively. Colour the markers based on the species

Exercise 8

a. Add an appropriate title to the plot using the layout function and title argument.
b. Add an appropriate x-axis label using the xaxis argument. xaxis takes a list of attribute values. Refer to the R reference page for more help.
c. Add an appropriate y-axis label.

Exercise 9

a. Use the range attribute in the list of values given to the xaxis argument to set the x-axis range from 1 to 10.
b. Similarly, set the y-axis range from 1 to 5.

Exercise 10

Try different layout options to further customize the font, axes etc… of the plot.




Getting started with Plotly: basic Plots

Plotly is a d3 based graphing library used to produce interactive and high quality graphs in R. In the following exercises, we will look at the basic plots’ syntax and some basic features in the plotly functions.
We will use datasets available in base R packages.

Refer to the documentation of the plotly packages when in need of help with the functions and arguments.
Also, refer to this link for figure references

Installation of the package is straight-forward as it is available on CRAN.
Use this command install.packages(‘plotly’) to install the package. Do not forget to load the package before trying out the exercises.

Answers to the exercises are available here.

Learn more about Plotly in Section 17 Interactive Visualizations with Plotly of the online course Data Science and Machine Learning Bootcamp with R.

Exercise 1

a. Generate a histogram for the first column of iris dataset using the plot_ly() function.
For the first run, supply only one argument to the function and see the message it returns.
identify the argument that you need to include to specify a chart type.

Exercise 2

Identify the argument to specify number of bins and generate a histogram with 20 bins using the same data.

Notice the behaviour of plot on mouse hover. There are also a few options available on the right top corner of the plot to zoom, save the plot etc.

Exercise 3

a. Generate a scatter plot for the first two columns of the iris dataset. Identify and use the appropriate arguments to get the plot with first column on the x axis and second column on y axis.
b. Using the color argument, specify the color such that data points are colored based on the Species column. HINT: color argument takes a vector of same length of number of data points data points with the level info.

Exercise 4

To the same code in the previous exercise, use the size argument to specify the markers’ size based on the third column of the iris dataset.

Exercise 5

a. Generate a line plot for 100 values of random normal distribution with the default mean and standard deviation.
HINT: Use index values on x axis. Use type="scatter" and mode="lines" to get a line chart

Exercise 6

b. Save the previous plot in an object p. Use layout function to add an appropriate title to the plot.

Exercise 7

To learn how to generate a bar plot, we will simulate sample data and look at how to prepare the data before plotting.
Run the below code to generate the data.
cat <- c(rep("A", 2), rep("B", 4), rep("C", 8))

Data has to be in the form of Levels and their Counts . Therefore, using table() function to summarize and as.data.frame to create a data frame.
df <- as.data.frame(table(cat))

a. Now, using type="bar" and the appropriate x and y arguments, create a bar graph.
b. Add color to each bar using color argument, based on the categorical levels.

Exercise 8

Pie chart is an alternative way of representing categorical data, but, when the levels in the data are more, bar chart is preferred.
Data has to be prepared in the same way as we do it for bar chart. The arguments vary a little. Instead of x and y, we use labels and values.

Generate a pie chart using the same data from the previous exercise and appropriate arguments.

Notice how the tick marks and the axes appear behind the chart.

Exercise 9

For the first column in the iris dataset, generate a box plot using the box trace type.
HINT:For a simple box plot, just the y argument and type argumnets are given.

Exercise 10

Add another argument to the code used in the previous exercies to generate mutliple box plots for the first column of iris dataset, where each box corresponds to data of particular Species.
HINT : Remember the argument we used to specify the color for each species in Exercise 3.

In the coming exercise sets on plotly, we will work on some advanced plots and see how to use argumnets from the layout function to manipulate the plot layout and settings.




Descriptive Analytics-Part 6: Interactive dashboard ( 2/2)

downloadDescriptive Analytics is the examination of data or content, usually manually performed, to answer the question “What happened?”.As this series of exercises comes to an end, the last part is going to be the development of a data product. Not everybody is able to code in R, so it is useful to be able to make GUIs in order to share your work with non-technical people. This part may be a little challenging, since it requires some basic knowledge of the shiny package. The outcome of this set of exercises will be almost like this web app (some variables are missing because I had to reduce the size of the data set).

In order to be able to solve this set of exercises you should have solved the part 0, part 1, part 2,part 3, and part 4 of this series but also you should run this script which contain some more data cleaning. In case you haven’t, run this script in your machine which contains the lines of code we used to modify our data set. This is the tenth set of exercise of a series of exercises that aims to provide a descriptive analytics solution to the ‘2008’ data set from here. This data set which contains the arrival and departure information for all domestic flights in the US from 2008 has become the “iris” data set for Big Data. The goal of Descriptive analytics is to inform the user about what is going on at the dataset. Before proceeding, it might be helpful to look over the help pages for the fluidPage, pageWithSidebar, headerPanel , sidebarPanel, selectInput, mainPanel, tabPanel, observe, verbatimTextOutput, renderPrint, shinyApp.

For this set of exercises you will need to install and load the package shiny.

install.packages('shiny')
library(shiny)

I have also changed the values of the DaysOfWeek variable, if you wish to do that as well the code for that is :
install.packages('lubridate')
library(lubridate)
flights$DayOfWeek <- wday(as.Date(flights$Full1_Date,'%m/%d/%Y'), label=TRUE)

Because the app requires some time to run, I have also removed the rows with missing values from the data set just to save some time.

flights <-flights[which(!is.na(flights['WeatherDelay'])),]
flights <-flights[which(!is.na(flights['ArrDelay'])),]

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page. Moreover it would be really nice of you to share the links of the apps you have developed. It would be a great contribution the community.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Create the user interface and set as the header of the web app : “Descriptive Analysis”

Exercise 2

Create a side panel.

Exercise 3

Create two select list input control. The former will contain the variables: CarrierDelay, WeatherDelay, NASDelay, SecurityDelay, LateAircraftDelay. The latter will contain the variables :Dest, Origin, UniqueCarrier, TailNum, CancellationCode.

Exercise 4

Create a set of radio buttons used to select a plot from a list ( Histogram, Scatter plot, Violin plot),and set as default plot the Histogram.

Exercise 5

Create a set of radio buttons used to select a plot from a list ( bar plot, pie chart, rose wind),and set as default plot the bar plot.

Exercise 6

Create a main panel.

Exercise 7

Create in the main panel two tabs named “Delays” and “Categorical” that will contain the plots of the exercises 4 and 5 respectively.

Exercise 8

Now that we are done with the user interface, create the server side of the app. Create the output of the first tab, which will be the plots from exercise 4 in respect to the first set of variables from exercise 3 ( notice that they are all continuous variables), bear in mind that at the scatter plot the x-axis should be the Full_Date and at the violin plot the x-axis should be the DayOfWeek as we did at the previous set of exercises. (please check out the first tab of the app, to make things more clear).

Exercise 9

Create the output of the second tab, , which will be the plots from exercise 5 in respect to the second set of variables from exercise 3 from the exercise 5, use the knowledge you applied ( or acquired at the previous exercises for the plots, make them as interesting as you can).(please check out the second tab of the app, to make things more clear).

Exercise 10

Launch the app.




Descriptive Analytics-Part 6: Interactive dashboard ( 1/2)

downloadDescriptive Analytics is the examination of data or content, usually manually performed, to answer the question “What happened?”.As this series of exercises comes to an end, the last part is going to be the development of a data product. Not everybody is able to code in R, so it is useful to be able to make GUIs in order to share your work with non-technical people. This part may be a little challenging, since it requires some basic knowledge of the shiny package. The outcome of this set of exercises will be almost like this web app (some variables are missing because I had to reduce the size of the data set).

In order to be able to solve this set of exercises you should have solved the part 0, part 1, part 2,part 3, and part 4 of this series but also you should run this script which contain some more data cleaning. In case you haven’t, run this script in your machine which contains the lines of code we used to modify our data set. This is the ninth set of exercise of a series of exercises that aims to provide a descriptive analytics solution to the ‘2008’ data set from here. This data set which contains the arrival and departure information for all domestic flights in the US from 2008 has become the “iris” data set for Big Data. The goal of Descriptive analytics is to inform the user about what is going on at the dataset. Before proceeding, it might be helpful to look over the help pages for the fluidPage, pageWithSidebar, headerPanel , sidebarPanel, selectInput, mainPanel, tabPanel, verbatimTextOutput, renderPrint, shinyApp.

For this set of exercises you will need to install and load the package shiny.

install.packages('shiny')
library(shiny)

I have also changed the values of the DaysOfWeek variable, if you wish to do that as well the code for that is :
install.packages('lubridate')
library(lubridate)
flights$DayOfWeek <- wday(as.Date(flights$Full1_Date,'%m/%d/%Y'), label=TRUE)

Because the app requires some time to run, I have also removed the rows with missing values from the data set just to save some time.

flights <-flights[which(!is.na(flights['WeatherDelay'])),]
flights <-flights[which(!is.na(flights['ArrDelay'])),]

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

Exercise 1

Create the user interface and set as the header of the web app : “Descriptive Analysis”

Exercise 2

Create a side panel.

Exercise 3

Create a select list input control that contains the functions : summary, str, head, tail, names, summary.

Exercise 4

Create a select list input control that contains the functions : mean, median, max, min, range, sd.

Exercise 5

Create a select list input control that contains the variables : ActualElapsedTime, CRSElapsedTime, AirTime, ArrDelay, DepDelay, TaxiIn, TaxiOut.

Exercise 6

Create a main panel.

Exercise 7

Create in the main panel two tabs named “Content” and “Measures” that will contain the output of the functions of exercise 3 and exercise 4 respectively.

Exercise 8

Now that we are done with the user interface, create the server side of the app and the output that is supposed to print the functions of the exercise 3. (please check out the first tab of the app, to make things more clear).

Exercise 9

Create the output of the second tab, combining the functions of exercise 4 and the variables from the exercise 5.(please check out the second tab of the app, to make things more clear).

Exercise 10

Launch the app.




Working with Shapefiles in R Exercises

R has many powerful libraries to handle spatial data, and the things that R can do with maps can only grow. This exercise tries to demonstrate a few basic functionalities of R while dealing with shapefiles.

A shapefile is a simple, nontopological format for storing the geometric location and attribute information of geographic features. Geographic features in a shapefile can be represented by points, lines, or polygons (ESRI). The geographic features are associated with an attribute table which is very similar to an R dataframe.

The rgdal package in R provides bindings to the popular Geospatial Data Abstraction Library (GDAL) for reading, writing and converting between spatial formats. We are using a very popular dataset of London sports participation shapefile (download here). The attributes Pop_2001 and Partic_Per represents the population of London Boroughs in 2001 and the percentage of the population participating in sporting activities.

Answers to the exercises are available here. If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Please install and load the package rgdal before starting the exercises.

Exercise 1
Read the London Sports map from the shapefile london_sports.shp .

Exercise 2
Change the coordinate system of the map to WGS 84.

Exercise 3
Find the names of the zones where sports participation rates is more than 25%.

Exercise 4
Plot the london map in Sky Blue, along with a title.

Exercise 5
Plot the zones in London with Sports Participation Rates less than 15% in red. Retain the earlier blue color for other zones.

Exercise 6
Plot the zones in London with Sports Participation Rates more than 25% in green. Retain the earlier color for other zones.

Exercise 7
Place a black circle marker at the centre of each zone. Retain previous maps.

Exercise 8
Put labels for each zone. Place the labels to the right of the black marker.

Exercise 9
Add another categorical attribute sports_part which has values "low", "medium" and "high" for sports participation rates less than equal to 15%, between 15 to 25% and greater than 25% respectively.

Exercise 10
Save the new map object with modified attribute table as a new shapefile “london_sport2.shp”.




Building Shiny App exercises part 4

APPLICATION LAYOUT & REACTIVITY
The fourth part of our series is “separated” into two “sub-parts”. In the first one we will start building the skeleton of our application by using tabsetPanel. This is how we will separate the sections of our app and also organize its structure better.
In the second part you will learn hot to load your dataset in RStudio and finally in the third one we will give life to your Shiny App! Specifically, you are going to have your first contact with reactivity and learn how to build reactive output to display in your Shiny app in a form of a data table initially.
Follow the examples below to understand the logic of the tools you are going to use and then enhance the app you started creating in part 1 by practising with the exercise set we prepared for you. Lets begin!

Answers to the exercises are available here.

If you obtained a different (correct) answer than those listed on the solutions page, please feel free to post your answer as a comment on that page.

Learn more about Shiny in the online course R Shiny Interactive Web Apps – Next Level Data Visualization. In this course you will learn how to create advanced Shiny web apps; embed video, pdfs and images; add focus and zooming tools; and many other functionalities (30 lectures, 3hrs.).

TABSET PANEL
In the example below you will see hot to add a tabsetPanel in your shiny app.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs"))
))

#server.R
library(shiny)
shinyServer(function(input, output) {
})

Exercise 1

Add a tabsetPanel to the mainPanel of your Shiny App.

TAB PANEL
In the example below you will see how to add tabPanel in your tabsetPanel.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1")
))))

#server.R
library(shiny)
shinyServer(function(input, output) {
})

Exercise 2

Place a tabPanel in the tabsetPanel you just added to your Shiny App. Name it “Data Table”.

Exercise 3

Put a second tabPanel next to the first one. Name it “Summary”.

LOAD DATASET
Now it is time to give your app a purpose of existence. This can happen with only one way. To add some data into it! As we told in part 1 we will create an application based on the famous (Fisher’s or Anderson’s) iris data set which gives the measurements in centimeters of the variables sepal length and width and petal length and width, respectively, for 50 flowers from each of 3 species of iris. The species are Iris setosa, versicolor, and virginica.
This is a “built in” dataset of RStudio that will help us create our first application.
But normally you want to analyze your own datasets. The first thing you should do in order to perform any kind of analysis on them is to load them properly. We will now see how to load a dataset in txt form from a local file using RStudio. Let’s go!
The process is quite simple. First of all you have to place the txt file that contains your dataset into the same directory that you are working, secondly press the “Import Dataset” button in RStudio and then “From Local File…”. Find the txt file in your computer and click “Open”, then press “Import”. That’s all! Your dataset is properly loaded in your directory and now you can work with it.
Please note that the purpose of this series is not to teach how to form your dataset before you load it nor how to “clean” it. You can gain more information about this subject from here. Our purpose is to teach you build your first Shiny App.

Exercise 4

Load the dataset you want to analyze (“something.txt”) from your computer to your directory with RStudio buttons.

INTRODUCTION TO REACTIVITY
From this point you are going to enter in the “Kingdom of Reactivity”. Reactive output automatically responds when your user interacts with a widget. You can create reactive output by following two steps. Firstly, add an R object to your ui.R. and then tell Shiny how to build the object in server.R.

1): Add an R object to the UI

Shiny provides a variety of functions that transform R objects into output for your UI as you can see below:

htmlOutput: raw HTML
imageOutput: image
plotOutput: plot
tableOutput: table
textOutput: text
uiOutput: raw HTML
verbatimTextOutput: text

To add output to the UI place the output function inside sidebarPanel or mainPanel in the ui.R script.
For example, the ui.R file below uses tableOutput to add a reactive line of text to “Tab Panel 1”. Nothing happens…for the moment!

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
})

Notice that datatableOutput takes an argument, the character string “dt1”. Each of the *Output functions require a character string that Shiny will use as the name of your reactive element. Users cannot see it and you will understand its role later.

Exercise 5

Add a datatableOutput to “Data Table”, name its argument “Table”.

2): Provide R code to build the object.

The code should be placed in the function that appears inside shinyServer in your server.R script.
This function is of great importance as it builds a list-like object named output that contains all of the code needed to update the R objects in your app. Be careful, each R object MUST have its own entry in the list.
You can create an entry by defining a new element for output within the function. The element name should match the name of the reactive element that you created in ui.R.
Each entry should contain the output of one of Shiny’s render* functions. Each render* function corresponds to a specific type of reactive object. You can find them below:

renderImage: images (saved as a link to a source file)
renderPlot: plots
renderPrint: any printed output
renderTable: data frame, matrix, other table like structures
renderText: character strings
renderUI: a Shiny tag object or HTML

Each render* function takes a single argument: an R expression which can either be one simple line of text, or it can involve many lines of code.
In the example below “dt1” is attached to the output expression in server.R and gives us the Data Table of “iris” dataset inside “Tab Panel 1”.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris)

})

Exercise 6

Add the appropriate render* function to server.R in order to create the Data table of the “iris” dataset. Hint: Use the output expression.

The dataTableOutput is your first contact with reactivity, in the next parts of our series you will use the rest of the Output functions that Shiny provides. But for now let’s experiment a little bit on this.
As you can see there is a text filter in your Data Table. You can deactivate it by setting searching to be “FALSE” as the example below.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(searching=FALSE))
})

Exercise 7

Disable the Text Filter of your Data Table. Hint: Use options, list and searching.

With the same logic you can disable the pagination that is displayed in your Data Table, as in the example below.

# ui.R

library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(searching=FALSE,paging=FALSE))
})

Exercise 8

Disable the Pagination of your Data Table. Hint: Use options, list, paging.
Now you can see how to display an exact number of rows (15) and enable filtering again.

# ui.R

library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(pageLength=15))
})

Exercise 9

Enable filtering again and set the exact number of rows that are displayed to 10. Hint: Use options, list, pageLength

We can also create a Length Menu in order to control totally the choices of the numbers of rows we want to be displayed. In the example below we assign every number to a menu label. 5 -> ‘5’, 10 -> ’10’, 15 -> ’15’,-1 -> ‘ALL’.

# ui.R
library(shiny)
fluidPage(
titlePanel("TabPanel"),
sidebarLayout(
sidebarPanel(h3("Menu")),
mainPanel(h3("Main Panel"),tabsetPanel(type = "tabs",
tabPanel("Tab Panel 1",dataTableOutput("dt1")),
tabPanel("Tab Panel 2"))
)))

#server.R
library(shiny)
shinyServer(function(input, output) {
output$dt1 <- renderDataTable(
iris,options = list(
lengthMenu = list(c(5, 15, 25,-1),c('5','15','25','ALL')),
pageLength = 15))
})

Exercise 10

Create a Length Menu with values (10,20,30,-1) and assign each one ot the values to the appropriate menu label. Hint: Use options, list, lengthMenu,pageLength.