How to build an R Shiny app from scratch?

Shiny is an R package that makes it easy to build interactive web applications using R. It allows you to create interactive dashboards, data visualizations, and web applications without requiring knowledge of HTML, CSS, or JavaScript. Here’s a step-by-step guide to help you get started with Shiny:

Step 1: Install R and RStudio

Make sure you have R and RStudio installed on your machine. You can download R from CRAN and RStudio from RStudio.

Step 2: Install Shiny

Open RStudio and install the Shiny package using the following command in the R console:

RCopy code

install.packages("shiny")

Step 3: Create a Simple Shiny App

Create a new R script or R Markdown file in RStudio and use the following code to create a simple Shiny app:

Code Display Component
Code Snippet
            # Load the Shiny library
            library(shiny)
            
            # Define the UI components
            ui <- fluidPage(
              # Application title
              titlePanel("My First Shiny App"),
            
              # Sidebar layout with input and output definitions
              sidebarLayout(
                # Sidebar panel for inputs
                sidebarPanel(
                  # Input: Slider for the number of bins
                  sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30)
                ),
            
                # Main panel for displaying outputs
                mainPanel(
                  # Output: Histogram
                  plotOutput("hist")
                )
              )
            )
            
            # Define the server function
            server <- function(input, output) {
              # Reactive expression to generate a histogram
              output$hist <- renderPlot({
                x <- faithful$waiting
                bins <- seq(min(x), max(x), length.out = input$bins + 1)
            
                hist(x, breaks = bins, col = 'darkgray', border = 'white', main = 'Histogram of waiting times',
                     xlab = 'Waiting time', ylab = 'Frequency')
              })
            }
            
            # Create the Shiny app object
            shinyApp(ui = ui, server = server)

This simple app consists of a slider input for the number of bins and displays a histogram based on the input. Save this script with a .R extension and run it in RStudio.

Step 4: Run the App

To run the Shiny app, open the script in RStudio and click the "Run App" button at the top of the script editor. This will launch the app in your default web browser.

Step 5: Explore and Customize

Once the app is running, you can interact with it. Experiment with changing the slider value and observe how the histogram updates dynamically. You can then customize and extend the app to include additional input widgets, output elements, and more complex logic based on your requirements.

Scroll to Top