Getting started with Shiny

Shiny is a package from RStudio that makes it incredibly easy to build interactive web applications with R. Have a look at some of the applications built using Shiny and perhaps you'll be as impressed as me. I will set up a local Shiny server on Ubuntu (12.04) running under VirtualBox. You don't actually need to install the server, to build Shiny applications, however some day I would like host my own Shiny server with a bunch of applications that I've built. To get started, let's check out the official tutorial on using Shiny. Fire up R and install the package:

install.packages("shiny")
library(shiny)
#run the first example
runExample("01_hello")

hello_shinyA web browser screenshot of what you would see when you run the example.

Shiny applications have two components: a user-interface definition (ui.R) and a server script (server.R):

ui.R

library(shiny)

# Define UI for application that plots random distributions 
shinyUI(pageWithSidebar(

  # Application title
  headerPanel("Hello Shiny!"),

  # Sidebar with a slider input for number of observations
  sidebarPanel(
    sliderInput("obs", 
                "Number of observations:", 
                min = 1,
                max = 1000, 
                value = 500)
  ),

  # Show a plot of the generated distribution
  mainPanel(
    plotOutput("distPlot")
  )
))

server.R

library(shiny)

# Define server logic required to generate and plot a random distribution
shinyServer(function(input, output) {

  # Expression that generates a plot of the distribution. The expression
  # is wrapped in a call to renderPlot to indicate that:
  #
  #  1) It is "reactive" and therefore should be automatically 
  #     re-executed when inputs change
  #  2) Its output type is a plot 
  #
  output$distPlot <- renderPlot({

    # generate an rnorm distribution and plot it
    dist <- rnorm(input$obs)
    hist(dist)
  })
})

Installing the Shiny server

Following the instructions from the Shiny installation guide for Ubuntu:

#if you don't have R installed already
sudo apt-get install r-base
#install dependencies
sudo apt-get install gdebi-core
#download the shiny server package
wget http://download3.rstudio.org/ubuntu-12.04/x86_64/shiny-server-0.4.0.8-amd64.deb
#install
sudo gdebi shiny-server-0.4.0.8-amd64.deb
#install shiny package
sudo su - \
  -c "R -e \"install.packages('shiny', repos='http://cran.rstudio.com/')\""

When you start the server, it will attempt to load its configuration from /etc/shiny-server/shiny-server.conf, which you need to create. For now my /etc/shiny-server/shiny-server.conf file contains the default configuration:

#create the directory
sudo mkdir /etc/shiny-server
#copy and paste the below
sudo vi /etc/shiny-server/shiny-server.conf

# Define the user we should use when spawning R Shiny processes
run_as shiny;

# Define a top-level server which will listen on a port
server {
  # Instruct this server to listen on port 3838
  listen 3838;

  # Define the location available at the base URL
  location / {
    # Run this location in 'site_dir' mode, which hosts the entire directory
    # tree at '/srv/shiny-server'
    site_dir /srv/shiny-server;
    
    # Define where we should put the log files for this location
    log_dir /var/log/shiny-server;
    
    # Should we list the contents of a (non-Shiny-App) directory when the user 
    # visits the corresponding URL?
    directory_index on;
  }
}

The default configuration above will create a single server listening on port 3838, serving any application contained within /srv/shiny-server/ at the root URL (/).

Let's create a new directory inside /srv/shiny-server/ called shinyApp1 and save the ui.R and server.R files from the start of this post in this directory.

ls /srv/shiny-server/shinyApp1
server.R  ui.R

To start the server (and other releated commands):

#start server
sudo start shiny-server
#stop server
sudo stop shiny-server
#restart server
sudo restart shiny-server
#reload
sudo reload shiny-server
#check status
status shiny-server

After we've started the server, if we direct our browser to http://localhost:3838/shinyApp1/, we should see this:

hello_shiny_localhost

Let's try another application taken from the Shiny page on Rstudio and save the two components inside /srv/shiny-server/shinyApp2:

ui.R

library(shiny)

shinyUI(bootstrapPage(

  selectInput(inputId = "n_breaks",
      label = "Number of bins in histogram (approximate):",
      choices = c(10, 20, 35, 50),
      selected = 20),

  checkboxInput(inputId = "individual_obs",
      label = strong("Show individual observations"),
      value = FALSE),

  checkboxInput(inputId = "density",
      label = strong("Show density estimate"),
      value = FALSE),

  plotOutput(outputId = "main_plot", height = "300px"),

  # Display this only if the density is shown
  conditionalPanel(condition = "input.density == true",
    sliderInput(inputId = "bw_adjust",
        label = "Bandwidth adjustment:",
        min = 0.2, max = 2, value = 1, step = 0.2)
  )

))

server.R

library(shiny)

shinyServer(function(input, output) {

  output$main_plot <- renderPlot({

    hist(faithful$eruptions,
      probability = TRUE,
      breaks = as.numeric(input$n_breaks),
      xlab = "Duration (minutes)",
      main = "Geyser eruption duration")

    if (input$individual_obs) {
      rug(faithful$eruptions)
    }

    if (input$density) {
      dens <- density(faithful$eruptions,
          adjust = input$bw_adjust)
      lines(dens, col = "blue")
    }

  })
})

shiny_app2_localhost

Building my own application

The bare minimum required for the ui.R and server.R files are:

ui.R

library(shiny)

# Define UI for miles per gallon application
shinyUI(pageWithSidebar(

  # Application title
  headerPanel("Title"),

  sidebarPanel(),

  mainPanel()
))

server.R

library(shiny)

shinyServer(function(input, output) {

})

To test run these files within R, use the runApp() function specifying the location of the ui.R and server.r files:

library(shiny)
setwd("C:/Users//Dave/Desktop/shiny/")
runApp('.')

I'll build an application using the iris dataset and allowing myself to produce scatter plots between the 4 leaf measurements. Here's the dataset, if you aren't familiar with it already:

head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

And here's the code I wrote:

ui.R

library(shiny)

# Define UI for iris application
shinyUI(pageWithSidebar(

  # Application title
  headerPanel("Using Shiny with the iris dataset"),

  # Sidebar with controls to select the variable to plot against mpg
  # and to specify whether outliers should be included
  sidebarPanel(
    selectInput("variable", "First variable:",
                list("Sepal length" = "Sepal.Length",
                     "Sepal width"  = "Sepal.Width",
                     "Petal length" = "Petal.Length",
                     "Petal width"  = "Petal.Width")),

    selectInput("variable2", "Second variable:",
                list("Sepal length" = "Sepal.Length",
                     "Sepal width"  = "Sepal.Width",
                     "Petal length" = "Petal.Length",
                     "Petal width"  = "Petal.Width"))
  ),

  mainPanel(
     h3(textOutput("caption")),
     plotOutput("plot")
  )
))

server.R

library(shiny)
library(datasets)
library(ggplot2)

data <- iris

# Define server logic required to plot variables
shinyServer(function(input, output) {

  # Create a reactive text
  text <- reactive({
     paste(input$variable, 'versus', input$variable2)
  })

  # Return as text the selected variables
  output$caption <- renderText({
    text()
  })

  # Generate a plot of the requested variables
  output$plot <- renderPlot({
     p <- ggplot(data, aes_string(x=input$variable, y=input$variable2, colour="Species")) + geom_point()
     print(p)
  })
})

And here are two screenshots of my new Shiny app!

my_shiny_app_1

my_shiny_app_2

To get it working on the shiny server, follow the instructions above and install ggplot2:

sudo su - \
  -c "R -e \"install.packages('ggplot2', repos='http://cran.ism.ac.jp/')\""

Now goto http://localhost:3838/my_app/ and voila!

my_shiny_app_server

Conclusions

Shiny is awesome!

Further reading

The Shiny tutorial

The Shiny server guide

Print Friendly, PDF & Email



Creative Commons License
This work is licensed under a Creative Commons
Attribution 4.0 International License
.
5 comments Add yours
      1. I understand up to sudo mkdir /etc/shiny-server, but are you actually creating these directories on your machine, or on the Ubuntu machine? If it is not on your machine, then how can you save it directly from RStudio?

        1. Everything is set up on the server (the Ubuntu machine). When I said RStudio, I meant you can use the text editor within it to save the code; all you need is a text editor to save the code in the directories. I use Vi, so the command is

          1. vi ui.R
          2. press i
          3. copy and paste the code
          4. press escape
          5. then hold shift and press z twice, i.e. ZZ

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.