Shiny Presentation Notes

Acknowledgments

Much of this presentation comes from Getting started with ShinyApps.io and the Teach yourself Shiny tutorial.

Using Shiny to Build Web Applications

You've done your research, produced results, and gotten it published. That's great! Now, the world at large deserves the chance to see your results and use your methods. We'd like to do this in a way that makes the research easily accessible and the software easy to use.

We are assuming that your work involves some computer software that has been developed to implement a method, produce reports, or otherwise do statistical analyses.

An obvious way to present your work is on the Internet. There are many ways to do this.

  • Link to the publication or other write up
  • put you code and test data on a repository like GitHub
  • produce an R package and post it to CRAN
  • build an application that implements your methods

Link to the publication

There are many ways to publicize your research. On your personal web page you can put links to your CV and to your publications. You can present at conferences and meetings. You can even use Twitter or Facebook. These all will do, but if you work involves software then the reader has to download and install programs and data and go through all the steps that that involves. It is quite likely that one step or another won’t work and your program won't run.

Post code, test data, and documentation on a repository

A repository service like GitHub may be used to distribute your code, documentation, and test data. This is similar to the previous method except that repositories like GitHub provide more features for sharing. All the code, documentation, and data can be stored so that when downloaded the directory structure is preserved and components end up where they belong. In addition, there is a mechanism for readers to make suggestions, additions, and corrections to you code and upload it for possible inclusion; under your control of course.

Produce an R package

For R programmers, producing an R package is a very useful way to make your software available to the R community. Properly constructed and tested packages can be downloaded and installed easily by an R user. A lot of the potential for problems is removed when software is distributed as an R packages. R packages can be distributed with the methods we've already discussed or they can be submitted to the CRAN repository for storage and distribution. CRAN is The Comprehensive R Archive Network. CRAN enforces a structure and testing framework on packages it accepts. This adds a layer of confidence that the software will perform as designed.

Implement your software as a web application

There are a lot of ways that one can build a web application. You can learn a programming language like Python or PHP (a useful endeavor in its own right) and develop a bunch of other web application skills. Or you can use Shiny. Shiny is a web application framework for R produced by the RStudio folks. No HTML, CSS, or JavaScript knowledge is required. You can use HTML, CSS, and such to change the look and feel of the programs and to add functionality, but they aren't required. Shiny provides a fairly easy way to turn you analyses into interactive web applications.

http://www.rstudio.com/
http://shiny.rstudio.com/

Shiny has been around for a couple of years. We’ve talked about it before but there has been some improvement to the product over the months so I wanted to take another look. I’m not a prolific R programmer nor am I an expert web application developer. So this look at Shiny is from someone who understands these things and can do a little but is not an expert.

First let’s look at some examples of what Shiny can do. These examples are from the Shiny web site: http://shiny.rstudio.com/gallery/

Shiny Overview

  • Every Shiny app has the same structure. At a minimum there are two R scripts saved together in a directory. Every Shiny app has ui.R and server.R files. These files implement the user interface and the working part of the application
  • You create a Shiny application by making a new directory and saving the ur.R and server.R files inside it.
  • You can run a Shiny app by giving the name of its directory to the R function “runApp()”.

Build a working program

Shiny apps have two components: A user interface script and a server script. There can be other files like help documentation, CSS files to change the look of the application, etc. But only the interface and server scripts are required.

First, make sure that Shiny is installed.

> install.packages("shiny")

Load the library

> library(shiny)

Run an example to make sure it works

> runExample("01_hello")

The Shiny package includes a bunch of examples. The runExample() function is a special version of the runApp() function that makes it easy to run the examples. There is also a special purpose web server so you can view your applications without having to install a full blown web server on your workstation.

Assuming the example runs OK, let’s move on and make a simple application.

Make a directory to hold our application.

$ cd ~
$ mkdir bin/demo1

Make the two files that all Shiny apps must have

$ cd ~/bin/demo1
$ touch ui.R
$ touch server.R

Add this code to ur.R.

library(shiny)
library(ggplot2)

dataset <- diamonds

shinyUI(pageWithSidebar(

  headerPanel("Diamonds Explorer"),

  sidebarPanel(

    sliderInput('sampleSize', 'Sample Size', min=1, max=nrow(dataset),
                value=min(1000, nrow(dataset)), step=500, round=0),

    selectInput('x', 'X', names(dataset)),
    selectInput('y', 'Y', names(dataset), names(dataset)[[2]]),
    selectInput('color', 'Color', c('None', names(dataset))),

    checkboxInput('jitter', 'Jitter'),
    checkboxInput('smooth', 'Smooth'),

    selectInput('facet_row', 'Facet Row', c(None='.', names(dataset))),
    selectInput('facet_col', 'Facet Column', c(None='.', names(dataset)))
  ),

  mainPanel(
    plotOutput('plot')
  )
))

Add this code to server.R

library(shiny)
library(ggplot2)

shinyServer(function(input, output) {

  dataset <- reactive(function() {
    diamonds[sample(nrow(diamonds), input$sampleSize),]
  })

  output$plot <- reactivePlot(function() {

    p <- ggplot(dataset(), aes_string(x=input$x, y=input$y)) + geom_point()

    if (input$color != 'None')
      p <- p + aes_string(color=input$color)

    facets <- paste(input$facet_row, '~', input$facet_col)
    if (facets != '. ~ .')
      p <- p + facet_grid(facets)

    if (input$jitter)
      p <- p + geom_jitter()
    if (input$smooth)
      p <- p + geom_smooth()

    print(p)

  }, height=700)

})

Run the application

The runApp function is similar to read.csv, read.table, and many other functions in R. The first argument of runApp is the filepath from your working directory to the app’s directory. The code above assumes that the app directory is in your working directory. In this case, the filepath is just the name of the directory.

> runApp(“~/bin/demo1”)
> ?runApp()

In an also be run in "showcase mode" to display to code along with the running application.

> runApp(“~/bin/demo1”, display.mode=”showcase”)

By default, the runApp() function will serve the application to the local machine only (localhost or 127.0.0.1). To make the application available to others, use the host=0.0.0.0 option.
> runApp(“~/bin/demo1”,host="0.0.0.0")

Deploy the application

There are a number of ways one could deploy a Shiny application. Using the little web server that comes with Shiny on you workstation probably wouldn't be appropriate. That server is designed for one user at a time. Plus it might interfere with other work you want to do.

For this demonstration we are using ShinyApps.io: https://www.shinyapps.io/. It is a hosting service operated by RStudio specifically for hosting Shiny applications. ShinyApps.io provides all kinds of convenience services to make it easy to deploy a Shiny application.

(we could also set up our own shiny server if needed)

There is a step by step guide for building a Shiny application and deploying on shinyapps.io: http://shiny.rstudio.com/articles/shinyapps.html

Demo Steps

Set the default path to the demo directory.

$ cd /bin/demo1

Run R…and test the application.

$ R
> library(shiny)
> runApp(“~/bin/demo1”)

Install the devtools package. It is needed to build the shinyapps software. In order to get devtools to install, I had to install a couple of dependencies.

At the Linux console, I installed libcurl4-openssl-dev is order to get the curl-config command.

$ sudo apt-get install libcurl4-openssl-dev

The curl-config command is needed for the RCurl R package that is a requirement for the devtools package.

> install.packages("RCurl")

Once the dependencies are installed we can proceed to install devtools.

> install.packages('devtools')

Restart your R session

Now, install the shinyapps package. It comes from the RStudio GitHub repository rather than CRAN.

> devtools::install_github('rstudio/shinyapps')

Load the shinyapps library

> library(shinyapps)

Go to https://www.shinyapps.io and log in.

A shinyapps.io application must be authorized and connected to my GitHub account. This is done using a token and a secret. These are generated by shinyapps.io and then copied to our computer. There is a shinyapps package function called setAccountInfo() that takes this authorization information and stores it. The authorization information is then used when we push our application to the shinyapps.io server.

Click on you username or user icon and select "Tokens". Now you can either Add a new token or use one previously set up. Click on Copy to Clipboard to copy the secret and tioken.

Now back in R on our computer…

Paste the code we just copied from shinyapps.io to the R console. Use the setAccountInfo() function to load out shinyapp authentication information. This is needed so we can upload the application to the shinyapp server.

> shinyapps::setAccountInfo(name='daleplummer', token='<token>', secret='<secret>')

Run the deployApp() function to upload and configure the application.

> deployApp()

The apps URL is http://daleplummer.shinyapps.io/demo1
Topic attachments
I Attachment Action Size Date Who Comment
shinyslides.odpodp shinyslides.odp manage 30.3 K 18 Nov 2014 - 15:42 DalePlummer Shiny presentation slides
shinyslides.pdfpdf shinyslides.pdf manage 30.7 K 18 Nov 2014 - 15:45 DalePlummer Shiny presentation slides (PDF)
Edit | Attach | Print version | History: r7 | r4 < r3 < r2 < r1 | Backlinks | View wiki text | Edit WikiText | More topic actions...
Topic revision: r3 - 18 Nov 2014, DalePlummer
 

This site is powered by FoswikiCopyright © 2013-2022 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding Vanderbilt Biostatistics Wiki? Send feedback