R Shiny Web App for Data Science - The Basics
Learn the basics of R Shiny by creating your first Web application using R
I just publish the first video of my new YouTube serie R Shiny Web App for Data Science", where I teach you how to create fully customized and beautiful R Shiny applications.
In this first episode you will learn how to:
access a gallery of hundreds of examples of R Shiny applications;
fully understand all the R code behind a basic R Shiny app;
get the intuition of how input-output interactions work in a Shiny app;
add a new text input in a Shiny app.
Check out the video now:
Starting with a Simple Single Layout
Let’s begin with the most basic Shiny layout structure. Here’s our first example:
# This is a Shiny web application. You can run the application by clicking
# the 'Run App' button above.
#
# Find out more about building applications with Shiny here:
#
# https://shiny.posit.co/
#
library(shiny)
# Define UI for application that draws a histogram
ui <- fluidPage(
# Application title
titlePanel("Old Faithful Geyser Data"),
# Sidebar with a slider input for number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$distPlot <- renderPlot({
# generate bins based on input$bins from ui.R
x <- faithful[, 2]
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white',
xlab = 'Waiting time to next eruption (in mins)',
main = 'Histogram of waiting times')
})
}
# Run the application
shinyApp(ui = ui, server = server)
This code demonstrates the fundamental structure of a Shiny application. The library(shiny)
command loads the Shiny package, which is essential for creating web applications. The ui
object defines the user interface using fluidPage()
, which creates a responsive layout that automatically adjusts to different screen sizes.
The titlePanel()
function creates the application header, while sidebarLayout()
establishes the classic two-column structure with a sidebar on the left and main panel on the right. Inside sidebarPanel()
, we use sliderInput()
to create an interactive slider that allows users to select the number of bins for the histogram. The mainPanel()
contains plotOutput()
, which displays the histogram generated by the server logic.
The server
function contains the reactive logic. The renderPlot()
function creates the histogram dynamically based on the user’s input from the slider. It accesses the faithful dataset (built into R), extracts the waiting times, creates bins based on the slider value, and generates the histogram with custom styling.
Adding More Interactive Elements
Now let’s enhance our application by adding more interactive elements to see how the layout adapts: