Loading...
Loading...

Building Web Apps with Shiny

Shiny is R's framework for creating interactive web applications. No HTML/CSS/JavaScript required!

1. Shiny Fundamentals

Core Concepts:

  • UI (User Interface): Defines the app layout and inputs
  • Server: Contains the app logic and computations
  • Reactivity: Automatic updates when inputs change
# Minimal Shiny app (app.R)
library(shiny)

ui <- fluidPage(
  sliderInput("num", "Choose number:", 1, 100, 50),
  plotOutput("hist")
)

server <- function(input, output) {
  output$hist <- renderPlot({
    hist(rnorm(input$num), main = paste(input$num, "Random Values"))
  })
}

shinyApp(ui, server)

2. Building Interfaces

Key Inputs:

ui <- fluidPage(
  # Common input types
  selectInput("var", "Variable:", names(mtcars)),
  numericInput("bins", "Bin count:", 10, min = 1),
  dateRangeInput("dates", "Date range:"),
  checkboxGroupInput("species", "Species:", 
                   choices = unique(iris$Species)),
  actionButton("go", "Update Results")
  
  # Layout with sidebar
  sidebarLayout(
    sidebarPanel(inputs...),
    mainPanel(outputs...)
  )
)

3. Reactive Programming

How Shiny Updates:

server <- function(input, output) {
  
  # Reactive expression (cached calculation)
  data <- reactive({
    iris[iris$Species == input$species, ]
  })
  
  # Observer (side effects)
  observeEvent(input$go, {
    showNotification("Data updated!")
  })
  
  # Render outputs
  output$plot <- renderPlot({
    ggplot(data(), aes(Sepal.Length, Sepal.Width)) + 
      geom_point()
  })
}

4. Professional Interfaces

Enhance UX with:

ui <- navbarPage("My App",
  tabPanel("Analysis",
           fluidRow(
             column(4, wellPanel(...)),
             column(8, ...)
           )),
  tabPanel("About", includeMarkdown("about.md")),
  
  # Add CSS/JavaScript
  tags$head(
    tags$style(HTML("
      body { background-color: #f9f9f9; }
      .well { border: 1px solid #ddd; }
    "))
  )
)

5. Building Dashboards

With shinydashboard:

library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(title = "Sales Dashboard"),
  dashboardSidebar(
    selectInput("region", "Region:", c("North", "South")),
    menuItem("Overview", tabName = "overview")
  ),
  dashboardBody(
    tabItems(
      tabItem("overview",
              fluidRow(
                valueBoxOutput("total_sales"),
                box(plotOutput("trend"))
              ))
    )
  )
)

6. Deploying Shiny Apps

Publishing Options:

# 1. shinyapps.io (free tier available)
rsconnect::deployApp()

# 2. RStudio Connect (enterprise)
# 3. Shiny Server (self-hosted)
# 4. Docker container

# Bundle for sharing
shiny::runUrl("https://example.com/app.zip")
0 Interaction
0 Views
Views
0 Likes
×
×
×
🍪 CookieConsent@Ptutorials:~

Welcome to Ptutorials

$ Allow cookies on this site ? (y/n)

top-home