Skip to content

Instantly share code, notes, and snippets.

@jamesmaino
Last active August 16, 2022 02:10
Show Gist options
  • Save jamesmaino/0e459d2d979d36422ed40e89f5301cea to your computer and use it in GitHub Desktop.
Save jamesmaino/0e459d2d979d36422ed40e89f5301cea to your computer and use it in GitHub Desktop.
Create new R shiny app in vscode

Create new R shiny app in vscode

Increasingly I am using vscode instead of RStudio for a consistent coding experience across languages. Here is how to start a new shiny app.

Make a ui.R script to hold the interface.

# Define UI for app that draws a histogram ----
ui <- fluidPage(

  # App title ----
  titlePanel("Hello Shiny!"),

  # Sidebar layout with input and output definitions ----
  sidebarLayout(

    # Sidebar panel for inputs ----
    sidebarPanel(

      # Input: Slider for the number of bins ----
      sliderInput(inputId = "bins",
                  label = "Number of bins:",
                  min = 1,
                  max = 50,
                  value = 30)

    ),

    # Main panel for displaying outputs ----
    mainPanel(

      # Output: Histogram ----
      plotOutput(outputId = "distPlot")

    )
  )
)

Make a server.R to hold the server logic.

# Define server logic required to draw a histogram ----
server <- function(input, output) {

  # Histogram of the Old Faithful Geyser Data ----
  # with requested number of bins
  # This expression that generates a histogram is wrapped in a call
  # to renderPlot to indicate that:
  #
  # 1. It is "reactive" and therefore should be automatically
  #    re-executed when inputs (input$bins) change
  # 2. Its output type is a plot
  output$distPlot <- renderPlot({

    x    <- faithful$waiting
    bins <- seq(min(x), max(x), length.out = input$bins + 1)

    hist(x, breaks = bins, col = "#75AADB", border = "white",
         xlab = "Waiting time to next eruption (in mins)",
         main = "Histogram of waiting times")

    })

}

Make a run_app.R script to set up a development server of the app that auto-refreshes with any saved change.

library(shiny)
options(shiny.autoreload = TRUE)
runApp()

Run run_app.R.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment