Shiny in R

📘 Introduction

Shiny is an R package for building interactive web applications directly from R without requiring knowledge of HTML, CSS, or JavaScript. Shiny applications allow users to interact with data, visualizations, and statistical models through a web browser using dynamic user interfaces and reactive programming.

Information

Shiny is widely used for creating dashboards, business intelligence applications, interactive reports, scientific tools, and machine learning interfaces.

đŸŽ¯ Why Learn Shiny?

  • Build interactive web applications using R.
  • Create dashboards for data visualization.
  • Develop data exploration tools.
  • Share analyses with non-programmers.
  • Deploy applications to the web.

📚 Shiny Application Architecture

Shiny Application
User Interface (UI)
Server Logic
Reactive Programming

đŸ“Ļ Installing Shiny

Install and Load Shiny

install.packages("shiny")

library(shiny)

📄 Basic Structure of a Shiny App

Every Shiny application consists of two main components:

ComponentPurpose
UIDefines the layout and user interface.
ServerContains application logic and computations.

🚀 Your First Shiny Application

Hello Shiny

library(shiny)

ui <- fluidPage(

  titlePanel("My First Shiny App"),

  h2("Welcome to Shiny!")

)

server <- function(

  input,
  output

) {

}

shinyApp(
  ui,
  server
)

đŸ–Ĩ User Interface Components

Shiny provides numerous UI components for collecting user input and displaying output.

FunctionPurpose
titlePanel()Application title.
sidebarLayout()Sidebar and main content layout.
sidebarPanel()Input controls.
mainPanel()Output area.
fluidRow()Responsive row layout.
column()Grid-based columns.

🎛 Input Controls

Common Input Widgets

ui <- fluidPage(

  textInput(
    "name",
    "Enter Name"
  ),

  numericInput(
    "age",
    "Age",
    20
  ),

  sliderInput(
    "marks",
    "Marks",
    min = 0,
    max = 100,
    value = 75
  ),

  checkboxInput(
    "graduate",
    "Graduate",
    FALSE
  ),

  selectInput(

    "course",

    "Course",

    choices = c(

      "R",
      "Python",
      "SQL"

    )

  )

)

📊 Displaying Text Output

Text Output

ui <- fluidPage(

  textInput(
    "name",
    "Name"
  ),

  textOutput(
    "welcome"
  )

)

server <- function(

  input,
  output

) {

  output$welcome <- renderText({

    paste(

      "Welcome",

      input$name

    )

  })

}

shinyApp(
  ui,
  server
)

📈 Displaying Plots

Interactive Plot

ui <- fluidPage(

  plotOutput(
    "scatterPlot"
  )

)

server <- function(

  input,
  output

) {

  output$scatterPlot <- renderPlot({

    plot(

      iris$Sepal.Length,

      iris$Petal.Length,

      col = "blue",

      pch = 19

    )

  })

}

shinyApp(
  ui,
  server
)

📋 Displaying Tables

Data Table

ui <- fluidPage(

  tableOutput(
    "dataTable"
  )

)

server <- function(

  input,
  output

) {

  output$dataTable <- renderTable({

    head(iris)

  })

}

shinyApp(
  ui,
  server
)

⚡ Reactive Programming

Shiny automatically updates outputs whenever reactive inputs change.

Reactive Expression

ui <- fluidPage(

  sliderInput(

    "number",

    "Choose Number",

    1,

    100,

    10

  ),

  textOutput(
    "result"
  )

)

server <- function(

  input,
  output

) {

  output$result <- renderText({

    input$number * 2

  })

}

shinyApp(
  ui,
  server
)

🔄 Using reactive()

The reactive() function stores calculations that automatically update when dependencies change.

Reactive Object

server <- function(

  input,
  output

) {

  doubled <- reactive({

    input$number * 2

  })

  output$result <- renderText({

    doubled()

  })

}

🖱 Using observeEvent()

observeEvent() executes code when a specific event, such as clicking a button, occurs.

Action Button

ui <- fluidPage(

  actionButton(

    "click",

    "Click Me"

  ),

  textOutput(
    "message"
  )

)

server <- function(

  input,
  output

) {

  observeEvent(

    input$click,

    {

      output$message <- renderText({

        "Button Clicked!"

      })

    }

  )

}

shinyApp(
  ui,
  server
)

📊 File Upload

Upload CSV File

ui <- fluidPage(

  fileInput(

    "file",

    "Choose CSV File"

  ),

  tableOutput(
    "preview"
  )

)

server <- function(

  input,
  output

) {

  output$preview <- renderTable({

    req(input$file)

    read.csv(

      input$file$datapath

    )

  })

}

shinyApp(
  ui,
  server
)

🎨 Layout Options

LayoutDescription
fluidPage()Responsive layout.
fixedPage()Fixed-width layout.
navbarPage()Multi-page navigation.
tabsetPanel()Tabbed interface.
sidebarLayout()Sidebar and content layout.

đŸ“Ļ Deploying a Shiny App

Shiny applications can be deployed locally or hosted online using services such as Posit Connect or ShinyApps.io.

Deploy with rsconnect

install.packages("rsconnect")

library(rsconnect)

deployApp()

🌍 Real-World Example

A sales manager wants an interactive dashboard to explore monthly sales. Users select a region, product category, and date range, while Shiny automatically updates tables, charts, and summary statistics without requiring any programming knowledge.

Sales Dashboard Example

library(shiny)

ui <- fluidPage(

  titlePanel("Sales Dashboard"),

  sidebarLayout(

    sidebarPanel(

      sliderInput(

        "year",

        "Year",

        2020,

        2026,

        2024

      )

    ),

    mainPanel(

      plotOutput(
        "salesPlot"
      )

    )

  )

)

server <- function(

  input,
  output

) {

  output$salesPlot <- renderPlot({

    plot(

      1:12,

      sample(

        100:500,

        12

      ),

      type = "b",

      col = "darkgreen",

      xlab = "Month",

      ylab = "Sales"

    )

  })

}

shinyApp(
  ui,
  server
)

🔄 Shiny Application Workflow

Design UI
Create Server Logic
Connect Inputs and Outputs
Add Reactive Behavior
Test Application
Deploy Application

📋 Common Shiny Functions

FunctionPurpose
shinyApp()Launches a Shiny application.
fluidPage()Creates a responsive page layout.
renderText()Generates text output.
renderPlot()Generates plots.
renderTable()Displays tables.
reactive()Creates reactive expressions.
observeEvent()Responds to user events.
req()Requires an input before continuing.

âš ī¸ Common Mistakes

MistakeExplanationSolution
Using reactive values incorrectlyReactive expressions must be called as functions.Access them using parentheses, such as value().
Ignoring req() for user inputsMissing inputs can cause runtime errors.Validate required inputs before processing.
Putting calculations outside the serverReactive updates may not occur.Place dynamic logic inside the server function.
Overusing reactive expressionsCan make applications difficult to maintain.Create only the reactive components that are necessary.

💡 Best Practices

  • Separate user interface design from server logic.
  • Use reactive programming to update outputs efficiently.
  • Validate user inputs with req() and input checks.
  • Keep server code modular and organized.
  • Optimize applications for performance when handling large datasets.
  • Test applications with different user inputs before deployment.
  • Use meaningful labels and intuitive layouts for better usability.

Best Practice

Shiny makes it possible to transform R scripts into interactive web applications with minimal web development knowledge. By combining reactive programming, well-structured user interfaces, and efficient server logic, you can build powerful dashboards and analytical tools that are accessible to a wide range of users.

📝 Summary

Shiny enables developers to create interactive web applications directly in R. In this chapter, you learned about the structure of a Shiny application, user interface components, server logic, input widgets, text, table, and plot outputs, reactive programming, event handling, file uploads, layouts, deployment, and application workflows. You also explored best practices for building responsive, maintainable, and user-friendly applications. Mastering Shiny allows you to share data analyses, dashboards, and machine learning models through dynamic web interfaces without requiring extensive web development experience.

>>"Shiny transforms R from a statistical programming language into a platform for building interactive, data-driven web applications."