What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Shiny in R to Build Interactive Web Apps (with code)

  • Jan 11, 2024
  • 8 Minutes Read
Shiny in R to Build Interactive Web Apps (with code)

R has proven to be a reliable tool for data scientists and analysts. Then, there is R Shiny, which comes in useful when it comes to sharing these findings with a larger audience, as it frequently requires the development of interactive and user-friendly interfaces. In this article, we will learn about Shiny in R and how it is used in creating interactive web apps.

What is Shiny in R?

R Shiny is a web application framework that allows users to build interactive, web-based dashboards, applications, and visualizations directly from their R scripts. Because of its simplicity of use and capacity to convert intricate analyses into interactive web applications without requiring a high level of web development expertise, Shiny—a program created by RStudio—has become incredibly popular.

Let’s see how we can use R Shiny. First of all, we have to install it. Be sure you have installed the required packages before exploring the world of R Shiny. The shiny and shinydashboard are the essential packages for creating Shiny applications. Let us install them using the following commands:

install.packages("shiny")
install.packages("shinydashboard")

 

Once installed, you can load these packages into your R environment:

library(shiny)
library(shinydashboard)

 

The R Shiny is a game changer for researchers, scientists, and students alike, providing an easy-to-use platform for creating interactive web applications to showcase our results and findings.

Basic Structure of a Shiny App

A typical Shiny app is made up of two primary parts: the server logic and the user interface (UI). The server logic performs the calculations and data manipulations, while the user interface (UI) is in charge of designing the application's structure and layout.

Here's a simple example of a Shiny app with a numeric input and a corresponding histogram:

ui <- fluidPage(
  titlePanel("Simple Shiny App"),
  sidebarLayout(
    sidebarPanel(
      numericInput("bins", "Number of bins:", 30)
    ),
    mainPanel(
      plotOutput("histogram")
    )
  )
)

server <- function(input, output) {
  output$histogram <- renderPlot({
    hist(rnorm(500), col = 'blue', main = 'Histogram', xlab = 'Value', xlim = c(-5, 5), breaks = input$bins)
  })
}

shinyApp(ui, server)

 

This basic example allows users to input the number of bins for a histogram through a numeric input and generates the corresponding histogram.

R Shiny for Creating Data Tables

One of the strengths of Shiny lies in its ability to create interactive data tables. The DT package in R helps us to create dynamic and feature-rich tables and display our data in them. The audiences then can use the table to interact with the data.

Let's consider an example of loading a dataset and allowing users to explore it interactively. First, we must install and load the DT package in our environment:

install.packages("DT")
library(DT)

 

Now let us code the Shiny app with interactive tables.

ui <- fluidPage(
  titlePanel("Interactive Data Table"),
  dataTableOutput("table")
)

server <- function(input, output) {
  data <- iris
  
  output$table <- renderDataTable({
    datatable(data, options = list(pageLength = 10))
  })
}

shinyApp(ui, server)

 

In this example, the DT package is used to create an interactive data table from the famous Iris dataset. Users can paginate, sort, and search through the data easily.

Shiny also supports real-time data updates, making it a powerful tool for monitoring and visualization. Let's create a real-time line chart that updates with new random data points every second:

data <- reactiveValues(values = numeric())

updateData <- function() {
  isolate({
    new_value <- runif(1)
    data$values <- c(data$values, new_value)
    if (length(data$values) > 10) {
      data$values <- tail(data$values, 10)
    }
  })
}

ui <- fluidPage(
  plotOutput("linePlot", width = "600px", height = "400px")
)

server <- function(input, output) {
  output$linePlot <- renderPlot({
    invalidateLater(1000)  # Update every second
    updateData()
    plot(data$values, type = "l", xlim = c(1, 10), ylim = c(0, 1), main = "Real-Time Line Graph", xlab = "Time", ylab = "Value")
  })
}

shinyApp(ui = ui, server = server)

 

Here we have used the Shiny library to create a web app that generates random numbers and displays them in a real-time line graph. The graph only shows the recent 10 values and the line is updated every second.

R Shiny Dashboard

With the Shiny Dashboard extension, you can make interactive dashboards with a predetermined design. It makes it simpler to create aesthetically pleasing and user-friendly interfaces by offering a framework for arranging and showcasing Shiny applications in a dashboard format.

Let's build a basic Shiny Dashboard with two tabs: one for a scatter plot and another for a bar chart.

ui <- dashboardPage(
  dashboardHeader(title = "Simple Shiny Dashboard"),
  dashboardSidebar(
    sidebarMenu(
      menuItem("Scatter Plot", tabName = "scatter"),
      menuItem("Bar Chart", tabName = "bar")
    )
  ),
  dashboardBody(
    tabItems(
      tabItem(tabName = "scatter",
              fluidRow(
                box(plotOutput("scatterPlot"))
              )),
      tabItem(tabName = "bar",
              fluidRow(
                box(plotOutput("barChart"))
              ))
    )
  )
)

server <- function(input, output) {
  output$scatterPlot <- renderPlot({
    plot(rnorm(100), rnorm(100), main = "Scatter Plot", xlab = "X", ylab = "Y")
  })
  
  output$barChart <- renderPlot({
    barplot(table(iris$Species), main = "Bar Chart", xlab = "Species", ylab = "Count")
  })
}

shinyApp(ui, server)

 

We've made a straightforward dashboard with two tabs for this example. A scatter plot and a bar chart are shown in the first and second tabs, respectively. The structure of Shiny Dashboard makes it possible to present various visualizations or components within the same application in an orderly manner.

Adding User Input Controls

User input controls, such as sliders, checkboxes, and dropdowns, can help us enhance the interactivity of our Shiny apps. Let's create an example where users can control the number of points in a scatter plot using a slider:

ui <- fluidPage(
  titlePanel("User Input Controls"),
  sidebarLayout(
    sidebarPanel(
      sliderInput("points", "Number of Points:", min = 10, max = 1000, value = 100)
    ),
    mainPanel(
      plotOutput("scatterPlot")
    )
  )
)

server <- function(input, output) {
  output$scatterPlot <- renderPlot({
    points <- input$points
    plot(rnorm(points), rnorm(points), main = paste("Scatter Plot (", points, " Points)"), xlab = "X", ylab = "Y")
  })
}

shinyApp(ui, server)

 

A slider input control is added to the sidebar in this example, allowing users to dynamically change the number of points in the scatter plot. The server logic's renderPlot function updates the plot based on the user's input.

Incorporating Reactive Outputs

Shiny's reactivity system is what makes it powerful and flexible. Reactive expressions and functions allow outputs to dynamically update based on changes in inputs. Let's build an app where the user can choose a dataset and visualize its summary statistics:

ui <- fluidPage(
  titlePanel("Reactive Outputs"),
  sidebarLayout(
    sidebarPanel(
      selectInput("dataset", "Choose Dataset:", choices = c("iris", "mtcars", "airquality"), selected = "iris")
    ),
    mainPanel(
      verbatimTextOutput("summaryText")
    )
  )
)

server <- function(input, output) {
  output$summaryText <- renderPrint({
    data <- switch(input$dataset,
                   "iris" = iris,
                   "mtcars" = mtcars,
                   "airquality" = airquality)
    summary(data)
  })
}

shinyApp(ui, server)

 

A dropdown menu (selectInput) in this tutorial example allows users to select a dataset (iris, mtcars, or airquality). Using the renderPrint function, the reactive output (summaryText) then displays the summary statistics of the selected dataset.

Conclusion

We've covered the fundamentals of R Shiny, looked at different examples, and explored the features of Shiny Dashboard in this blog. Its true strength is in fusing statistical analysis with interactive visualization, allowing us to convey complex insights into our study in a user-friendly manner for the audience. 

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Abhisek Ganguly
Passionate machine learning enthusiast with a deep love for computer science, dedicated to pushing the boundaries of AI through academic research and sharing knowledge through teaching.