Accessing and Manipulating Biological Databases Exercises (Part 1)

In the exercises below we cover how we can Access and Manipulate Biological Data bases through rentrez & seqinr packages

Install Packages
rentrez
seqinr

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

Print all the available data bases which you can access through rentrez package

Exercise 2

Print all the searchable terms in a database

Exercise 3

Display the details of any database of your choice

Exercise 4

Retrieve and print 10 ids of nucleotide sequences from nuccore database about Human.

Exercise 5

Retrieve and print 20 ids of protein sequences from protein database about Human.

Learn more about Data Pre-Processing in the online course R Data Pre-Processing & Data Management – Shape your Data!. In this course you will learn how to:

  • import data into R in several ways while also beeing able to identify a suitable import tool
  • use SQL code within R
  • And much more

Exercise 6

Create a Fasta File for a particular human protein sequence from the listed ids.

Exercise 7

Create a Fasta File for a particular human nucleotide sequence from the listed ids.

Exercise 8

Open the Nucleotide Fasta file and print the details using seqinr package.

Exercise 9

Open the Protein Fasta file and print the details using seqinr package

Exercise 10

Open the Nucleotide Fasta file and print only sequence from the created Fasta file striping all other information.




Shiny Application Layouts Exercises (Part-2)

SHINY APPLICATION LAYOUTS-PLOT PLUS COLUMNS

In the second part of our series we will build another small shiny app but use another UI.

More specifically we will present the example of a UI with a plot at the top and columns at the bottom that contain the inputs that drive the plot. For our case we are going to use the diamonds dataset to create a Diamonds Analyzer App.

This part can be useful for you in two ways.

First of all, you can see different ways to enhance the appearance and the utility of your shiny app.

Secondly you can make a revision on what you learnt in the “Building Shiny App” series as we will build basic shiny stuff in order to present it in the proper way.

Read the examples below to understand the logic of what we are going to do and then test your skills with the exercise set we prepared for you. Lets begin!

Answers to the are available here.

Shiny Installation

In order to create the app we have to install and load the package shiny.

Exercise 1

Install and load shiny.

Grid Layout

The sidebarLayout uses Shiny’s grid layout functions. Rows are created by the fluidRow function and include columns defined by the column function. Column widths should add up to 12 within a fluidRow.
The first parameter to the column function is it’s width. You can also change the position of columns to decide the location of UI elements. You can put columns to the right by adding the offset parameter to the column function. Each unit of offset increases the left-margin of a column by a whole column.

Now let’s begin to build our UI. First of all we will place the fluidpage with a title as below:

#ui.R
library(shiny)
shinyUI(fluidPage(
title = "Diamonds",
h4("Diamonds Analyzer")

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

Exercise 2

Create the initial UI of your app and name it “Diamonds Analyzer”.

You can use the fluidrow function with the column function of width =2 inside of it like this:
#ui.R
library(shiny)
shinyUI(fluidPage(
title = "Diamonds",
h4("Diamonds Analyzer"),
fluidRow(column(2),
column(2),
)

))

Exercise 3

Create a fluidrow with two columns of width = 4 inside it. NOTE: Do not expect to see something yet.

Now it is time to fill these columns with some tools that will help us determine the variables that we are going to use for our plot.
In the first 4 columns we will put a selectInput as the code below.
#ui.R
fluidRow(column(4,
h4("Variable X"),
selectInput('x', 'X', names(diamonds)))

Exercise 4

Put a selectInput in the first 4 columns of your UI. Name it “Variable X”. HINT:Use names to get the names of the dataset diamonds as inputs.

Now let’s move to the next four columns. We are going to put in there another selectInput and select the second of the dataset’s names as default. We are also going to see what offset does by setting it to 1 and then deactivating it again like the example below. You can use the code as it is or change the parameters given to understand the logic behind its use.
#ui.R
offset = 1,
selectInput('y', 'Y', names(dataset), names(dataset)[[2]])

Exercise 5

Create a selectInput from column 5 to column 8. Choose the second of the dataset’s name as default. Name it “Variable Y”. HINT: Use names to get the names of the dataset diamonds as inputs.

Exercise 6

Set the offset parameter to 1 from columns 5 to 8.

Now let’s call our plot and put it on the top of our UI. Look at the example below.

Exercise 7

Place the plot on the top of your UI. HINT: Use plotOutput and hr. NOTE: You are not going to see the plot in your UI because you have not created the server side yet.

We are going to create a reactive expression in order to combine the selected variables into a new data frame.Look at the example:
#server.R
selectedData <- reactive({
diamonds[, c(input$x, input$y)]
})

Exercise 8

Create a reactive expression in order to combine the selected variables into a new data frame. HINT: Use reactive.

Now plot your new data frame like the example:
#server.R
output$plot <- renderPlot({
plot(selectedData())
})

Exercise 9

Plot your data frame. HINT: Use renderPlot.

As mentioned before the width of our UI is equal to 12 columns. So what is goint to happen if we a add a new column of width = 4 next to the other two? You have to find out in order to understand better how it works.

Exercise 10

Create a new selectInput and try to put it next to “Variable Y”. Try to explain the result. NOTE: You do not have to connect it with your plot.




Forecasting for small business Exercises (Part-3)

Uncertainty is the biggest enemy of a profitable business. That is especially true of small business who don’t have enough resources to survive an unexpected diminution of revenue or to capitalize on a sudden increase of demand. In this context, it is especially important to be able to predict accurately the change in the markets to be able to make better decision and stay competitive.

This series of posts will teach you how to use data to make sound prediction. In the last set of exercises, we’ve seen how to make predictions on a random walk by isolating the white noise components via differentiation of the term of the time series. But this approach is valid only if the random components of the time series follow a normal distribution of constant mean and variance and if those components are added together in each iteration to create the new observations.

Today, we’ll see some transformations we can apply on the time series make them stationary, especially how to stabilise variance and how to detect and remove seasonality in a time series.

To be able to do theses exercise, you have to have installed the packages forecast and tseries.

Answers to the exercises are available here.

Exercise 1
Use the data() function to load the EuStockMarkets dataset from the R library. Then use the diff() function on EuStockMarkets[,1] to isolate the random component and plot them. This differentiation is the most used transformation with time series.

We can see that the mean of the random component of the time series seems to stay constant over time, but the variance seems to get bigger near 1997.
Exercise 2
Apply a the log() function on EuStockMarkets[,1] and repeat the step of exercise 1. The logarithmic transformation is often used to stabilise non constant variance.

Exercise 3
Use the adf.test() function from the tseries package to test if the time series you obtain in the last exercise is stationary. Use a lag of 1.

Exercise 4
Load and plot the co2 dataset from the R library dataset. Use the lowess() function to create a trend line and add it to the plot of the time series.

By looking at the last plot, we can see that the time series oscillate from one side to the other of the trend line with a constant period. That characteristic is called seasonally and is often observed in time series. Just think about temperature, which change predictably from season to season.
Exercise 5
To eliminate the upward trend in the data use the diff() function and save the resulting time series in a variable called diff.co2. Plot the autocorrelation plot of diff.co2.

Exercise 6
This last autocorrelation plot has years for unit which is not really intuitive in our scenario. Make another autocorrelation plot where the x axis has months as units. By looking at this plot, can you tell what is the seasonal period of this time series?

Another way to verify if the time series show seasonnality is to use the tbats function from the forecast package. As his named says, this function fits a tbats model on the time series and return a smooth curve that fit the data. We’ll learn more about that model in a future post.
Exercise 7
Use the tbats function on the co2 time series and store the result in a variable called tbats.model. If the time series show sign of seasonality, the $seasonal.periods value of tbats.model will store the period value, else the result will be null.

Exercise 8
Use the diff() function with the appropriate lag to remove the seasonality of the co2 time series, then use it again to remove the trend. Plot the resulting random component and the autocorrelation plot.

Exercise 9
Apply the adf test, the kpss test and the Ljung-Box test on the result of the last exercise to make sure that the random component is stationary.

Exercise 10
An interesting way to analyse a time series is to use the decompose() function which uses a moving average to estimate the seasonal, random and trend component of a time series. With that in mind, use this function and plot each component of the co2 time series.




Shiny Application Layouts Exercises (Part-1)

Shiny Application Layouts part 1

Welcome to the first part of our new series “Shiny Application Layouts”. As you can understand from the title we will see how to organize the output of our application in various ways. For this reason we will build together 10 simple apps that will help you understand what kind of interfaces shiny provides.

In this part we will see tabsets which is one of the simplest ways to organize our app. This part can be useful for you in two ways.
First of all, as already mentioned, you can see different ways to enhance the appearance and the utility of your shiny app.
Secondly you can make a revision on what you learnt in Shiny Apps series as we will build basic shiny staff in order to present it in the proper way.

In part 1 we will use the dataset data which is loaded in R by default and we will create three tabPanel. Each one of them with its own utility.

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.

Tabsets

We use tabset in our application application to organize output. Firstly install the shiny package and then call it in a new r script of your working directory.
You can use install.packages() and library() for these.

Exercise 1

Install and load the shiny package.

Tab Panels

Tabsets can be created by calling the tabsetPanel function. Each tab panel includes a list of output elements.

In this case we will create a histogram, a summary and table view of the data, each rendered on their own tab.

Let’s start by creating the basic interface like the example below: As we know the UI includes three basic parts (headerPanel, sidebarPanel, mainPanel).
#ui.R
library(shiny)

shinyUI(pageWithSidebar(
headerPanel("Example"),
sidebarPanel(),
mainPanel()
))

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

Exercise 2

Create the basic interface, name it “APP 1”.

Secondly let’s fill our sidebar with some widgets. We will create radioButtons and sliderInput to control the random distribution and the number of observations. Look at the example.
#ui.R
library(shiny)

shinyUI(pageWithSidebar(
headerPanel("Example"),
sidebarPanel(
radioButtons("cho", "Choice:",
list("One" = "one",
"Two" = "two",
"Three" = "three",
"Four" = "four"
br(),

sliderInput("n",
"Number of observations:",
value = 50,
min = 1,
max = 100)
),
mainPanel()
))

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

Exercise 3

Put radioButtons inside sidebarPanel.The four choices will be “Normal”, “Uniform”, “Log-Normal”, “Exponential” and the name of it “Distributions”.

Exercise 4

Put sliderInput under radioButtons. Its values should be from 1 to 1000 and the selected value should be 500. Name it “Number of observations”.

It is time to create three tabsets in order to place there a plot, summary, and table view of our dataset. More specifically we will use a plotOutput, a verbatimTextOutput and a tableOutput. Look at the code and the build your own.
#ui.R
tabsetPanel(
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary", verbatimTextOutput("summary")),
tabPanel("Table", tableOutput("table"))
)

Exercise 5

Create your tabsetPanel which will include the tabPanel.

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 6

Create the first tabPanel for your Plot.Use plotOutput.
Create the second tabPanel for your Summary Statistics.Use verbatimTextOutput.
Create the third tabPanel for your Table.Use tableOutput.

Tabs and Reactive Data

Working with tabs into our user-interface magnifies the importance of creating reactive expressions for our data. In this example each tab provides its own view of the dataset. We have to mention that the bigger the dataset the slower our app will be.
We should use a Reactive expression to generate the requested distribution. This is called whenever the inputs change. The renderers are defined below then all use the value computed from this expression.
#server.R
data <- reactive({
dist <- switch(input$dist,
norm = rnorm,
unif = runif,
lnorm = rlnorm,
exp = rexp,
rnorm)

dist(input$n)
})

Exercise 7

Put data() in the correct place of your code in order to activate it.

Now we should generate a plot of the data. Note that the dependencies on the data are both tracked by the dependency graph.

As you can see from the code below we use the renderPlot function to create the reactive plot and inside there we use the hist function in order to create the histogram.
#server.R
output$plot <- renderPlot({
dist <- input$dist
n <- input$n

hist(data())
})

Exercise 8

Create a reactive histogram inside the tabPanel “Plot”

Let’s print a summary of the data in the tabPanel “Summary”. As you can see below we will use renderPrint for our case and the function summary.
#server.R
output$summary <- renderPrint({
summary(data())
})

Exercise 9

Print tha dataset’s summary in the tabPanel “Summary”.

Last but not least we will create an HTML table view of the data. For this we will use renderTable and data.frame function.
#server.R
output$table <- renderTable({
data.frame(x=data())
})

Exercise 10

Create a data table in the tabPanel “Table”.




Forecasting for small business Exercises (Part-1)


Uncertainty is the biggest enemy of a profitable business. That is especially true of small business who don’t have enough resources to survive an unexpected diminution of revenue or to capitalize on a sudden increase of the demand. In this context, it is especially important to be able to predict accurately the change in the markets to be able to make better decision and stay competitive.

This series of posts will teach you how to use data to make sound prediction. In this first set of exercises, you’ll learn the essential concepts we’ll use throughout the series: how to use the fundamental R tools for time series analysis, how to verify if a time series is stationary and how to make prediction in that context.

Answers to the exercises are available here.

To be able to do theses exercises, you have to have installed the R packages forecast and tseries.

Exercise 1
Use the data function to load the treering dataset from the R library. This dataset is loaded as an R time series object which is a vector whose value are ordered chronologically. Look at the structure of this ts object and use another function to find the number of observations in the dataset.

Exercise 2
Use the function window(ts, start, end) to select the observations in the treering dataset from the year 1500 to the year 2000.

Exercise 3
Do a basic plot of the treering dataset and use the abline function to add an horizontal red line representing the mean of the dataset.

Looking at the previous plot, we get the sense that these values are randomly distributed around the red line who represent the mean of the dataset. Also the magnitude of the random fluctuation of the points seems to stay stable over time. Such a time series is called “stationary” and it is a propriety we prefer to observe in a time series when we want to make predictions.

To make sure that the time series is stationary, we’ll draw the autocorrelation plot and run the Box-Ljung test, Kwiatkowski-Phillips-Schmidt-Shin test and the Augmented Dickey–Fuller test on the dataset.

Exercise 4
Load the forecast package and use the Acf function to draw the autocorrelation plot of the time series.

Exercise 5
Use the Box.test function to apply the Box-Ljung test on the data set. Set the parameter lag to the maximum value of Lag in the previous plot.

Exercise 6
Load the tseries package and apply the Kwiatkowski-Phillips-Schmidt-Shin test by using the kpss.test function on the data.

Exercise 7
Use the adf.test function to apply the Augmented Dickey–Fuller t-statistic test on the dataset. Set the argument alternative to “stationary”.

Exercise 8
Use the Holt-Winters Filtering method to apply an exponential smoothing on the time series. Use the function HoltWinters with the parameters beta and gamma set to “FALSE” to select the exponential smoothing and start the function at the first observation of the dataset. Store the result in a variable named HW.

Exercise 9
With the forecast.HoltWinters function make predictions for the next 5 years, store the results in a variable named prediction and print it to the screen.

Exercise 10
Use the plot.forecast function from the forecast package to plot your predictions.




Data Structures Exercises (Part 2)

In the Exercises we will cover Hashes, Factors and Zoo in R

Answers to the exercises are available here.

Learn more about Data Structures in the online course
R Data Pre-Processing & Data Management – Shape your Data!
. In this course you will learn how to:

  • Convert your data in R
  • Use SQL query embedded in R
  • Work with different data management packages like dplyr
  • And much more

Exercise 1

Create a Hash based Key Value Pairs with three employees, with Employees as the key and the name as the values.

Exercise 2

Create Hash of an Employee with the Name, Age, Address & SSN as the key and the details of the employee as the values

Exercise 3

Create Hash and use names function to give names to the key.

Exercise 4

Create a factor based on marks of students and print the summary of the same.

Exercise 5

Create a factor based on heights and print the levels and summary for the heights factor

Exercise 6

Create a factors of 10 random values between 1 and 100, with on repeating values and also check the variable is a factor

Exercise 7

Create a factor based on Age of students and plot a graph based on the age.

Exercise 8

Create a random factor based on 0 & 1 and give assign false for 0 and true for 1 and check the variable by print the type of the variable.

Exercise 9

Create a random factor based on 0 & 1 and give assign false for 0 and true for 1 and assign new 11 the value as False.

Exercise 10

Create a data Frame of dates and return of company and use zoo
to convert the data.




Building Shiny App exercises part 10

SHINY DASHBOARD STRUCTURE & APPEARANCE

Finally we reached in the final part of our series. At this part we will see how to improve the structure and the appearance of our dashboard even more, according to our preferences and of course make it more attractive to the user. Last but not least we will see the simplest and easiest way to deploy it.

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.

infoBox

There is a special kind of box that is used for displaying simple numeric or text values, with an icon.The example code below shows how to generate infoBox. The first row of infoBox uses the default setting of fill=FALSE.

Since the content of an infoBox will usually be dynamic, shinydashboard contains the helper functions infoBoxOutput and renderInfoBox for dynamic content.
#ui.R
library(shinydashboard)

dashboardPage(
dashboardHeader(title = "Info boxes"),
dashboardSidebar(),
dashboardBody(
# infoBoxes with fill=FALSE
fluidRow(
# A static infoBox
infoBox("New Orders", 10 * 2, icon = icon("credit-card")),
# Dynamic infoBoxes
infoBoxOutput("progressBox"),
infoBoxOutput("approvalBox")
)))

#server.R
shinyServer(function(input, output) {
output$progressBox <- renderInfoBox({
infoBox(
"Progress", paste0(25 + input$count, "%"), icon = icon("list"),
color = "purple"
)
})
output$approvalBox <- renderInfoBox({
infoBox(
"Approval", "80%", icon = icon("thumbs-up", lib = "glyphicon"),
color = "yellow"
)
})
})

Exercise 1

Create three infoBox with information icons and color of your choice and put them in the tabItem “dt” under the “DATA-TABLE”.

To fill them with a color follow the example below:
#ui.R
library(shinydashboard)

dashboardPage(
dashboardHeader(title = "Info boxes"),
dashboardSidebar(),
dashboardBody(
# infoBoxes with fill=FALSE
fluidRow(
# A static infoBox
infoBox("New Orders", 10 * 2, icon = icon("credit-card"),fill = TRUE),
# Dynamic infoBoxes
infoBoxOutput("progressBox"),
infoBoxOutput("approvalBox")
)))
#server.R
shinyServer(function(input, output) {
output$progressBox <- renderInfoBox({
infoBox(
"Progress", paste0(25 + input$count, "%"), icon = icon("list"),
color = "purple",fill = TRUE
)
})
output$approvalBox <- renderInfoBox({
infoBox(
"Approval", "80%", icon = icon("thumbs-up", lib = "glyphicon"),
color = "yellow",fill = TRUE
)
})
})

Exercise 2

Fill the infoBox with the color you selected in Exercise 1. HINT: Use fill.

Exercise 3

Now enhance the appearance of your tabItem named “km” by setting height = 450 in the four box you have there.

Skins

There are a number of color themes, or skins. The default is blue, but there are also black, purple, green, red, and yellow. You can choose which theme to use with dashboardPage(skin = "blue"), dashboardPage(skin = "black"), and so on.

Exercise 4

Change skin from blue to red.

CSS

You can add custom CSS to your app by adding code in the UI of your app like this:
#ui.R
dashboardPage(
dashboardHeader(title = "Custom font"),
dashboardSidebar(),
dashboardBody(
tags$head(tags$style(HTML('
.main-header .logo {

font-weight: bold;
font-size: 24px;
}
')))
)
)

Exercise 5

Change the font of your dashboard title by adding CSS code.

Long titles

In some cases, the title that you wish to use won’t fit in the default width in the header bar. You can make the space for the title wider with the titleWidth option. In this example, we’ve increased the width for the title to 450 pixels.
#ui.R
dashboardPage(
dashboardHeader(
title = "Example of a long title that needs more space",
titleWidth = 450
),
dashboardSidebar(),
dashboardBody(

)
)

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

Exercise 6

Set your titlewidth to “400” and then set it to the default value again.

Sidebar width

To change the width of the sidebar, you can use the width option. This example has a wider title and sidebar:

#ui.R
library(shinydashboard)
dashboardPage(
dashboardHeader(
title = "Title and sidebar 350 pixels wide",
titleWidth = 350
),
dashboardSidebar(
width = 350,
sidebarMenu(
menuItem("Menu Item")
)
),
dashboardBody()
)

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

Exercise 7

Set sidebar width to “400” and then return to the default one.

Icons

Icons are used liberally in shinydashboard. The icons used in shiny and shinydashboard are really just characters from special font sets, and they’re created with Shiny’s icon() function.

To create a calendar icon, you’d call:
icon("calendar")

The icons are from Font-Awesome and Glyphicons. You can see lists of all available icons here:

http://fontawesome.io/icons/
http://getbootstrap.com/components/#glyphicons

Exercise 8

Change the icon of the three menuItem of your dashboard. Select whatever you like from the two lists above.

Statuses and colors

Many shinydashboard components have a status or color argument.

The status is a property of some Bootstrap classes. It can have values like status="primary", status="success", and others.

The color argument is more straightforward. It can have values like color="red", color="black", and others.

The valid statuses and colors are also listed in ?validStatuses and ?validColors.

Exercise 9

Change the status of the three widget box in the tabItem named “km” to “info”, “success” and “danger” respectively.

Shinyapps.io

The easiest way to turn your Shiny app into a web page is to use shinyapps.io, RStudio’s hosting service for Shiny apps.

shinyapps.io lets you upload your app straight from your R session to a server hosted by RStudio. You have complete control over your app including server administration tools.

First of all you have to create an account in shinyapps.io.

Exercise 10

Publish your app through Shinyapps.io




Data Structures Exercises (Part-1)

R Programming has various Data Structures for efficient manipulation of Data.
Following are the list of data structures supported by R.

1. Vectors
2. Lists
3. Matrix
4. Data frame
This exercise helps through various operations of R Data structures.

Answers to the exercises are available here.

Exercise 1

Create an atomic vector of Character type, double type, logical type , integer type, complex type and raw type

Exercise 2

Check whether each of the created data structure is of vector type as well as check the class of each of the data.

Exercise 3

Create a List of heterogeneous data, which include numeric, character and logical vectors and prints the lists.

Exercise 4

Create a matrix of 3 rows and 4 columns which stores data from 1 to 12 and arrange the value row wise.

Exercise 5

Create a matrix of 3 rows and 4 columns which stores random data and arrange the matrix column wise

Exercise 6

Create two 2 x 2 matrices with random values and perform all arithmetic operations with those two and print the resultant matrices

Exercise 7

Create a random matrix having values between 1 and 1000 and print the matrix and transpose of the matrix

Exercise 8

Create Data Frames which contain details of 5 employees and display the same.

Exercise 9

Create Data Frames which contain details of 5 employees and display summary of the data

Exercise 10

Create a Data Frame of 5 employees and display the details of First and Last Employee and Names of All employees.




Data Science for Operational Excellence (Part-1)



R has many powerful libraries to handle operations research. This exercise tries to demonstrate a few basic functionality of R while dealing with linear programming.
Linear programming is a technique for the optimization of a linear objective function, subject to linear equality and linear inequality constraints.
The lpsolve package in R provides a set of functions to create models from scratch or use some prebuilt ones like the assignment and transportation problems.
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 lpsolve and igraph before starting the exercise.

Answers to the exercises are available here.

Exercise 1
Load packages lpSolve and igraph. Then, take a look at lp.assign to see how it works.

Exercise 2
Create a matrix representing the cost related to assign 4 tasks(rows) to 4 workers(cols) by generating integer random numbers between 50 and 100, with replacement. In order to make this exercise reproducible, define seed as 1234.

Exercise 3
Who should be assign to each task to obtain all the work done at minimal cost?

Exercise 4
Based on the resource allocation plan, how much we will spend to get all this work done?

Exercise 5
Take a look at lp.transport to see how it works. Set up the cost matrix by generating integer random numbers between 0 and 1000, without replacement. Consider that will be 8 factories(rows) serving 5 warehouses(cols).

Exercise 6
Set up the offer constraint by generating integer random numbers between 50 and 300, without replacement.

Exercise 7
Set up the demand constraint by generating integer random numbers between 100 and 500, without replacement.

Exercise 8
Find out which factory will not use all its capacity at the optimal cost solution.

Exercise 9
What is the cost associated to the optimal distribution?

Exercise 10
Create adjacency matrix using your solution in order to create a graph using igraph package.




Building Shiny App Exercises (part-9)

Shiny Dashboard Overview

In this part we will “dig deeper” to discover the amazing capabilities that a Shiny Dasboard provides.
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.

The dashboardPage function expects three components: a header, sidebar, and body:
#ui.R
dashboardPage(
dashboardHeader(),
dashboardSidebar(),
dashboardBody()
)

For more complicated apps, splitting app into pieces can make it more readable:

header <- dashboardHeader()

sidebar <- dashboardSidebar()

body <- dashboardBody()

dashboardPage(header, sidebar, body)

Now we’ll look at each of the three main components of a shinydashboard.

HEADER

A header can have a title and dropdown menus. The dropdown menus are generated by the dropdownMenu function. There are three types of menus – messages, notifications, and tasks – and each one must be populated with a corresponding type of item.

Message menus

A messageItem contained in a message menu needs values for from and message. You can also control the icon and a notification time string. By default, the icon is a silhouette of a person. The time string can be any text. For example, it could be a relative date/time like “5 minutes”, “today”, or “12:30pm yesterday”, or an absolute time, like “2014-12-01 13:45”.
#ui.R
dropdownMenu(type = "messages",
messageItem(
from = "Sales Dept",
message = "Sales are steady this month."
),
messageItem(
from = "New User",
message = "How do I register?",
icon = icon("question"),
time = "13:45"
),
messageItem(
from = "Support",
message = "The new server is ready.",
icon = icon("life-ring"),
time = "2014-12-01"
)
)

Exercise 1

Create a dropdownMenu in your dashboardHeader as the example above. Put date, time and generally text of your choice.

Dynamic content

In most cases, you’ll want to make the content dynamic. That means that the HTML content is generated on the server side and sent to the client for rendering. In the UI code, you’d use dropdownMenuOutput like this:

dashboardHeader(dropdownMenuOutput("messageMenu"))

Exercise 2

Replace dropdownMenu with dropdownMenuOutput and the three messageItem with messageMenu.

The next step is to create some messages for this example.The code below does this work for us.
# Example message data in a data frame
messageData <- data.frame(
from = c("Admininstrator", "New User", "Support"),
message = c(
"Sales are steady this month.",
"How do I register?",
"The new server is ready."
),
stringsAsFactors = FALSE
)

Exercise 3

Put messageData inside your server.r but outside of the shinyServer function.

And on the server side, you’d generate the entire menu in a renderMenu, like this:
output$messageMenu <- renderMenu({
# Code to generate each of the messageItems here, in a list. messageData
# is a data frame with two columns, 'from' and 'message'.
# Also add on slider value to the message content, so that messages update.
msgs <- apply(messageData, 1, function(row) {
messageItem(
from = row[["from"]],
message = paste(row[["message"]], input$slider)
)
})

dropdownMenu(type = "messages", .list = msgs)
})

Exercise 4

Put the code above(output$messageMenu) in the shinyServer of server.R.

Hopefully you have understood by now the logic behind the dynamic content of your Menu. Now let’s return to the static one in order to describe it a little bit more. So make the proper changes to your code in order to return exactly to the point we were after exercise 1.

Notification menus

A notificationItem contained in a notification contains a text notification. You can also control the icon and the status color. The code below gives an example.
#ui.r
dropdownMenu(type = "notifications",
notificationItem(
text = "20 new users today",
icon("users")
),
notificationItem(
text = "14 items delivered",
icon("truck"),
status = "success"
),
notificationItem(
text = "Server load at 84%",
icon = icon("exclamation-triangle"),
status = "warning"
)
)

Exercise 5

Create a dropdownMenu for your notifications like the example. Use text of your choice. Be careful of the type and the notificationItem.

Task menus

Task items have a progress bar and a text label. You can also specify the color of the bar. Valid colors are listed in ?validColors. Take a look at the example below.
#ui.r
dropdownMenu(type = "tasks", badgeStatus = "success",
taskItem(value = 90, color = "green",
"Documentation"
),
taskItem(value = 17, color = "aqua",
"Project X"
),
taskItem(value = 75, color = "yellow",
"Server deployment"
),
taskItem(value = 80, color = "red",
"Overall project"
)
)

Exercise 6

Create a dropdownMenu for your tasks like the example above. Use text of your choice and create as many taskItem as you want. Be carefull of the type and the taskItem.

Disabling the header

If you don’t want to show a header bar, you can disable it with:

dashboardHeader(disable = TRUE)

Exercise 7

Disable the header.

Now enable it again.

Body

The body of a dashboard page can contain any regular Shiny content. However, if you’re creating a dashboard you’ll likely want to make something that’s more structured. The basic building block of most dashboards is a box. Boxes in turn can contain any content.

Boxes

Boxes are the main building blocks of dashboard pages. A basic box can be created with the box function, and the contents of the box can be (most) any Shiny UI content. We have already created some boxes in part 8 so lets enhance theis appearance a little bit.
Boxes can have titles and header bar colors with the title and status options. Look at the examples below.

box(title = "Histogram", status = "primary",solidHeader = TRUE, plotOutput("plot2", height = 250)),

box(
title = "Inputs", status = "warning",
"Box content here", br(), "More box content",
sliderInput("slider", "Slider input:", 1, 100, 50),
textInput("text", "Text input:")
)

Exercise 8

Give a title of your choice to all the box you have created in your dashboard except of the three widgets’ box.

Exercise 9

Change the status of the first three box to “primary” and the last three to “warning”.

Exercise 10

Transform the headers of your first three box to solid headers.