A series of participative sessions among coding enthusiasts interested in data analysis, number crunching and teaching of statistics. Quite R-based but welcoming other languages and tools.
An introduction to Shiny II
Written on October 16, 2018 by Antonio Elías Fernández
This is our second session introducing Shiny, an R package that allows to develop interactive Apps in a familiar framework for regular R-users. During the first session we focused on the structure and workflow basics, and now, we will go further on input and output objects, reactivity, layouts and data handling.
All these functionalities will be reviewed by product of developing a Shiny App. It will provide the grades to our students and, at the same time, they will be able to explore the data set by interacting with the App. In addition to show static information, we will incorporate some reactive features conditional to the user, we will add the possibility of loading data and we will arrange all this in a friendly interface.
A relevant task in teaching duties is the continuous and final assessment. Typically, we communicate this information via a static documents such as PDFs, spreadsheets or using the institutional platform (Aula Global).
From my point of view and as former professor of Statistics, it is an excellent moment to put into practice the contents of the subject. At this moment, students are excited (worried) about the results and probably, for the first time, they will pay attention to us. Maybe they are looking forward to know for example,
Personal marks and global marks as well.
How they perform with respect to others.
The expected mark in the final exam given his/her own continuous assessment (regression).
If there is any difference by some characteristics…
The following link contains a folder with the final App and the data sets we are going to use along the session.
The data set contains information about students from the last year, 2017-2018 course, and the current 2018-2019 course. In addition to some categorical varibles such as gender, high school track or Identification Number (NIU), it provides the continuous assessment and the final exam grades.
Notice that for the students of 2018-2019 we do not have the final exams grades since they have not done it yet.
The next part is just a proposal of analysis of the data set above. Any suggestions?
Descriptive Statistics
Firstly, we could add some summary statistics just by,
In addition, we could provide the ranking of a given student by,
Secondly, we would like to include histograms, violin plots and bar plots. For a given user, we could also include his/her location on the plots.
Regression
One could think about predicting the final grade of the former students given the continuous assessment. In this case, given one NIU we would like to provide the expected final grade.
Central Limit Theorem and Resampling
Typically, the last sessions of a basic Statistics course are devoted to the Central Limit Theorem, Confidence Interval and Hypothesis Testing. This part of the App will try to illustrate that the sample mean is a random variable and that we cannot compare sample means for testing if there are significant differences.
The following code estimates empirically the distribution of the mean for a given characteristics. Then, we can visualize how far is one empirical distribution from the other. Below it is ton for testing if there is a difference in continuous assessment between males and females. As default it takes $100$ samples of size $30$ but it would be illustrative to leave them as inputs of our App.
We could think also about differences between students from a science track or from no science tracks,
We have plotted the sample distribution of the mean by the categorical variable. As we commented before, it would be interesting if the student could tune the number of samples and the sample size for a visualization of the CLT.
Baselines Developing Our Shiny App
This section contains the first steps for building our App. For more details, the reader could check An Introduction to Shiny.
Any single Shiny App must have the following parts:
ui (User Interface) - nested R functions that assemble an HTML user interface for the App. It is in charge of the contents and style of the App,
server - a function with instructions on how to build and rebuild the R objects displayed in the UI. Its arguments are the inputs and the outputs of the App. In this part is where our R code is going to be included.
shinyApp - combines ui and server into an App.
As it was shown in our last post about Shiny, just one single R script could contain the whole application. The skeleton of this one-file-Shiny-App would be,
However, when the App becomes more complicated and we want to add more functionalities the R script above could become hard to manage. Fortunately, if desired, one could create a folder for holding the App and split the code. As mandatory files, it must have two .R files named ui.R and server.R. We will also create the main.R for running the App by runApp(path), being path the location of our folder. However, if we set our folder as working directory, R-Studio recognizes the App.
From R code to a Shiny App
One reasonable way of building a Shiny App is starting from the R code that the App will requires. Then we must start thinking about Inputs and Output objetcs, in other words, what we need from the user and what we want to show to the user.
At the Introduction we wrote some R script with some ideas about the results we would like to show to the student. In this section, we will go little by little adding it to a Shiny App and including reactivity.
Reactivity is what makes Shiny App special and one of the most complex issues while developing. Master this feature will allow to do more sophisticated Apps, however, just some intuitions and insights could improve a lot our developing skills. For a more detailed information, I refer to the reader to this talk from 2016 Shiny Developers Conference.
Data handling
First things first, we have to load the data set. Assuming that the file is at the server (our App folder in this case), we could read it by adding to the server.R our favorite command for loading data. Here we will use the function read_csv() from the package readr. The command library(readr) can be added at the beginning of the main.R file.
Typically, for each subject we have two or three small groups and it would be desirable to add an option for choosing the file of the group to which the student belongs to. This option implicates our first reactive action, the user has to take a decision and our App has to take into account this action when loading the data. Then, we will have to include an Input Object at ui.R and a reactive function at the server.R. The function switch() is useful for assigning an action to different choices.
Another option that we could consider it is to provide to the App the ability of uploading a file from a local directory. For doing this, we can use the fileInput() at the ui.R for gathering the file directory. Then, this can be used at the server.R.
Both options above work. However, if we do not add the trigger, the App will try to read a .csv from a location that has not been provided.
Printing Data
The simplest choice would be to print the dataset with a table.
We could print just the information of one student that provides his/her NIU (student identification number). For that, it would be needed an input object for the NIU.
But we could also use a function that embedded JavaScript code providing an interactive table from the package DT (add library(‘DT’) at main.R). This table allows for filtering, searching values, etc.
Group Tab
Below we propose a code for summarizing continuousAssessment and HighSchoolTrack by a plot and some statistics.
If we allow to the user to select one variable, we have to control whether the variable is categorical or numerical. For categorial variables, we will display a frequency table and a bar plot. For a continuous variable, we will show a summary and an histogram. For doing this, we will use the functions renderUI() and uiOutput().
In addition, if the variable is continuous and a histogram is plotted, we would like to tune the number of bins.
Personal Tab
Given a NIU, we will show the personal grades as well as some location statistics with respect to the class grades.
Final Grades Prediction Tab
Here we just consider to predict the final grade given the continuous assessment. However, the regression model is defined as a reactive value and, therefore, the code below could be easily extended for more general cases.
Comparison Tab
Layout and themes
Here comes the part related to tidy up our outputs in a nice interface and framework. I propose the following design and we will see how to incorporate these sections in our ui.R.
There is a wide list of choices and they can be combined as desired.
The following code provides the main layout structure where outputs have to be added.
All the code above is composed by functions that embed HTML code. Run the code for “translating” the R functions into HTML. As it was shown in post, ui.R is simply a part of web site and it is easy to add Cascading Style Sheets or JavaScript files for improving the appearance of the App.
But even without knowledge of web site programming, there are R functions for these purposes. An example is to include a theme in our App that includes automatically a Cascading Style Sheet with predefined options. Run the code below for running a widget (JS) that allows to visualize our App with different themes.