R

How to Build Interactive Web Apps with Shiny in R

Owing it to the R Shiny framework, a bundle from RStudio, creating dynamic web apps with R is relatively easy. The benefit of Shiny is that it makes it possible to put your R code on the web, making it more accessible to a wider range of users. With R Shiny, you can create very powerful data reports and visuals that allow the user to analyze the data set. Along with Shiny components, the HTML elements may be used to design the program’s content. Today’s article walks you through the process of constructing an interactive Web application employing R’s Shiny package. For this, make sure to have “RStudio” installed already.

Install the Shiny Package in RStudio

Before moving towards creating an interactive web application within RStudio, we should have the “Shiny” package already installed in it. For this, you need to expand the “Tools” menu of the RStudio followed by the “Install Packages” option. Within the opened window, you have to mention the package that you want to install, i.e. “shiny,” and tap on the “Install” button. The RStudio will install the shiny package in the RStudio console.

Get Started with Shiny in R

To get started with Shiny in R, you need to create a new R file using the “File” menu located in the first place of RStudio. Expand it and use the “New File” option followed by the “R Script” option. The “untitled” script file will be opened in RStudio. Rename it as an “R” file in your desired location.

Now, load the necessary packages required to build an interactive application in R, i.e. using the “library” function of R. The “if” statements are used to install the packages that were not previously installed. The Shiny package is used to build an interactive interface for web applications along with some graphical visualizations. The “dplyr” package is mainly used to ease the data manipulation in R by utilizing some useful functions.

Lastly, the “ggplot2” package is loaded as a great source of data visualization by creating customized and powerful graphs.

if (!requireNamespace("shiny", quietly = TRUE)) {

  install.packages("shiny")

}

if (!requireNamespace("dplyr", quietly = TRUE)) {

  install.packages("dplyr")

}

if (!requireNamespace("ggplot2", quietly = TRUE)) {

  install.packages("ggplot2")

}

library(shiny)

library(dplyr)

library(ggplot2)

Build an Interactive Exam Grading System

Within this tutorial, we will create an “Exam Grading System” for students to get their achieved grades via the marks that are obtained out of 100. The provided script is the “ui” component of a Shiny app which specifies the design and look of the program. The program generates a fluidPage, an adaptable design that can be scaled to adjust for the browser window.

A “titlePanel” and a “sidebarLayout” are the offspring of the “fluidPage”. The “Exam Grading System” title of the program is all that is displayed in the “titlePanel”. A “sidebarPanel” and a “mainPanel” are the two sections that the “sidebarLayout” uses to split the application into. A pair of inputs are included in the “sidebarPanel”: a “textAreaInput” named “score” plus an “actionButton” named “calculate”.

One score per line can be entered for each student using the “textAreaInput”. The grade assessment can be started by the use of “actionButton”. A pair of outputs are present in the “mainPanel”: a “tableOutput” named “Result” plus a “plotOutput” named “ResultGraph”. Both the “tableOutput” and the “plotOutput” will present the calculation’s findings in the form of a graph.

ui <- fluidPage(

  titlePanel("Exam Grading System"),
  sidebarLayout(
    sidebarPanel(
      textAreaInput("score", "Enter Scores for Students (one per line):", ""),
      actionButton("calculate", "Let's Calculate Grades")
    ),
    mainPanel(
      tableOutput("Result"),
      plotOutput("ResultGraph")
    ) )  )

The server method establishes the application’s server-side logic. The marks for students are initially stored in a reactive variable named “data”. For this, the “calculate” button is monitored by the “observeEvent” method of R. After the button is triggered, the code initially converts the values that are entered in the text field input to numerical values.

Each score is followed by a line break using the “\n” to input a new score at the very next line. The method places whatever score it finds in the “data” variable. If a user has input no score, the method shows a message with an error.

server <- function(input, output) {

  data <- reactiveVal(NULL)

  observeEvent(input$calculate, {

    score <- as.numeric(unlist(strsplit(input$score, "\n")))

    if (length(score) > 0) {

      data(score)

  } else {

    data(NULL)

    showModal(modalDialog(

      title = "Error",

      "Error: Please add value!",

       easyClose = TRUE

    ))

  }

})

Two outputs, “output$Result” plus “output$ResultGraph”, are specified to show the student marks and achieved grades. The renderTable() dynamic method produces a data table of the student’s test marks and grades which is labeled as “output$Result”. The renderPlot() method, which is likewise reactive, generates a bar graph for student grades and saves it in the “output$ResultGraph” output similarly.

They will, therefore, be reviewed each time the input data updates. The if (!is.null(data())) expression determines whether or not the data that is being received is null. The “if” statement’s script is performed if it is not empty. A vector of scores for students makes up the input “data”. Every student is given a grade based on their score using the case_when() method. A data frame containing the student grades and test marks is created using the data.frame() method. The following columns are added to the data frame: “Student”, “Score”, and “Grade”. The grade distribution is compiled in a table called “GradeCount” using the table() method.

output$Result <- renderTable({

  if (!is.null(data())) {

    grades <- case_when(

      data() > 80 ~ "A",

      data() > 60 ~ "B",

      data() > 40 ~ "C",

      data() > 30 ~ "D",

      TRUE ~ "F"

    )

    data.frame(Student = 1:length(data()), Score = data(), Grade = grades)

    }

  })

output$ResultGraph <- renderPlot({

  if (!is.null(data())) {

    grades <- case_when(

      data() > 80 ~ "A",

      data() > 60 ~ "B",

      data() > 40 ~ "C",

      data() > 30 ~ "D",

      TRUE ~ "F"

    )

    GradeCount <- table(grades)

The bar chart is created using the “ggplot2” library. Count (the total number of students who obtained each grade) and the column Grade are created in a DataFrame. A bar graph with the “Grade” data on the “x-axis” and the “Count” data on the “y-axis” is produced using the geom_bar() method. The stat = “identity” option instructs ggplot2 to utilize the actual data without any kind of transformation. A title, an x-axis label, and a y-axis label are all added via the “labs” method. The bar’s colors are assigned using the scale_fill_manual() method. Unnecessary grid lines and overlay components are removed using the theme_minimal() method. The shinyApp(ui, server) method builds an app.

      ggplot(data = data.frame(Grade = names(GradeCount), Count = as.numeric(GradeCount)),
             aes(x = Grade, y = Count, fill = Grade)) +
        geom_bar(stat = "identity") +
        labs(title = "Grade Distribution",
             x = "Grade",
             y = "Count") +
        scale_fill_manual(values = c("A" = "green", "B" = "purple", "C" = "pink",
                                     "D" = "orange", "F" = "red")) +
        theme_minimal()
    }
  })
}
shinyApp(ui, server)

Upon running this code, we got an interactive interface where we added some marks and clicked on the “Let’s Calculate Grades” button.

The table that contains the student scores and grades is displayed, followed by the Bar graph of the grade distribution in different colors.

Conclusion

This guide explains the importance of the Shiny package usage in the R language via RStudio. To supplement our explanation, we constructed an interactive web application for students’ grading system in the R code by utilizing the “Shiny” package.

About the author

Saeed Raza

Hello geeks! I am here to guide you about your tech-related issues. My expertise revolves around Linux, Databases & Programming. Additionally, I am practicing law in Pakistan. Cheers to all of you.