an introduc+on to r shiny - university of...

25
A web applica+on framework for R R Shiny makes it very easy to build interac+ve web applica+ons with R Much of this introductory informa+on is taken directly from the available tutorial from R Studio h<p://shiny.rstudio.com/tutorial/ An Introduc+on to R Shiny (shiny is an R package by R Studio)

Upload: lytruc

Post on 31-Mar-2018

221 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

•  Awebapplica+onframeworkforR

•  RShinymakesitveryeasytobuildinterac+vewebapplica+onswithR

•  Muchofthisintroductoryinforma+onistakendirectlyfromtheavailabletutorialfromRStudio– h<p://shiny.rstudio.com/tutorial/

AnIntroduc+ontoRShiny(shinyisanRpackagebyRStudio)

Page 2: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Tutorial“HelloShiny!”OpenRandrunthetutorialexample

> library(shiny)> runExample("01_hello")

Page 3: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

•  Shinyapplica+onshavetwocomponents:– auser-interfacedefini/on(UI)filecalledui.R

•  Thissourcecodeisusedtoset-upwhattheuserwillactuallyseeinthewebapp,i.e.thelayoutofthewebpage–  Title,sliders,widgets,plots,loca+onofitemsonthepage,etc.

•  Thissourcecodeisalsousedtoacceptinputfromtheuser–  e.g.Itrecognizeswhattheuserhasenteredintheslider

–  aserverscriptfilecalledserver.R•  Thissourcecodedoesthecomputa+onalRwork“underthehood”withfamiliarfunc+onssuchashist(),plot(),etc.•  Thissourcecodecontainstheinstruc+onsthatyourcomputerneedstobuildyourapp

•  ThesetwosourcefilesworktogethertocreateyourRShinywebapplica+on

Page 4: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Let’stakeacloselookatthesetwofilesforthe“HelloShiny!”app

Page 5: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Exampleui.r filefromtutorial“HelloShiny!”(seRng-upthestructureofthewebpage)

Definesidebar:Putthesliderforinputinthesidebarpanelandnametheinputas“bins”.

Createalayoutwithasidebar(1/3spaceofpage)andmainarea(2/3spaceofpage).

Defineyoursliderandsetini+alseRngsforslider(value=30).

Definemainpanel:Putthegeneratedplotinthemainpanel.

Giveyouroutputplotaname,suchas“distPlot”.Thisnamewillalsobeusedintheserver.rfile.

Page 6: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Set-upargumentsforthehist()func+onbasedonuser-input“bins”fromwebapp.

Generatethehist()plotwithgivenarguments.

Exampleserver.r filefromtutorial“HelloShiny!”(the“underthehood”computa+ons)

Nameofoutputplotstatedintheui.rfile,or“distPlot”.

Page 7: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

<folder,directorypath>

my_app

ui.R server.R

TomakeanRShinyapp,startwiththisfolder/file/filenamestructure.Putbothfiles(namedexactlyui.Randserver.R)intoasinglefoldernamedforyourapp.Thisisthe‘bare-bones’structureforaShinyapp.Asyougetmorecomplex,youmayincludeotherthingsinthisfolder,suchasadatafile,orthe‘global.R’file,butthat’sfurtherdowntheroad.

Folder/FilestructureforRshinyapp

Page 8: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

RunninganRShinyApp•  EveryShinyapphasthesamestructure:–  twoRscriptssavedtogetherinadirectory.Ataminimum,aShinyapphasui.Randserver.Rfiles.

•  YoucancreateaShinyappbymakinganewfiledirectoryandsavingaui.Randserver.Rfileinsideit.Eachappwillneeditsownuniquedirectory(orfolder).

•  YoucanrunaShinyappbygivingthenameofitsdirectorytothefunc+onrunApp().

> library(shiny)> runApp("my_app")

Page 9: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Runningthe“Helloshiny”appdirectlyfromtheui.Randserver.Rfiles

•  AaerpuRngthetwofilesfromthe“HelloShiny!”tutorialintomylocaldirectorycalled"Stat_6220/R-shiny/hello_shiny",Iwasabletorunthesameappwiththefollowingcommands:

•  WhichmeansIcannoweditandplayaroundwiththecodetocreateanewapp.

> setwd("Stat_6220/R-shiny")> library(shiny)> runApp("hello_shiny")

Page 10: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

MynewRShinyapp

•  Airqualitysca<erplot:Ozonevs.Wind–  Inputslider:sizeofpoints

> setwd("Stat_6220/R-shiny")> library(shiny)> runApp("hello_shiny_2")

Page 11: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Choosingsmallpoints.

Choosinglargepoints.

Webaccessibleversion:h<p://shiny.rhondadecook.com/hello_shiny_2/

Page 12: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

library(shiny)

shinyUI(fluidPage(titlePanel("Hello Shiny 2!"),sidebarLayout(

sidebarPanel(sliderInput("size",

"Point size:", min=0.5, max=10, value=1)

),mainPanel(

plotOutput("airPlot"))

)))

Exampleui.rfilefromtutorial“HelloShiny2!”(seRng-upthestructureofthewebpage)

Putthesliderforinputsoverinthesidebarpanel.

Createalayoutwithasidebar(1/3space)andmainarea(2/3space).

Defineyourslider,user-definedinput,andini+alseRngsforslider.

Putthegeneratedplotinthemainpanel.

Giveyouroutputplotaname,suchas“airPlot”.Thisnamewillalsobeusedintheserver.rfile.

Page 13: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

library(shiny)

shinyServer(function(input,output){output$airPlot<-renderPlot({

x<-airquality[,3]y<-airquality[,1]

plot(x,y,col="#0000ff20",pch=16, cex=input$size, xlab="Wind", ylab="Ozone",cex.lab=1.5)

points(x,y,col=1,pch=1,cex=input$size)}, height = 400, width = 400)

})Generatetheplotbasedonuser-input“size”fromwebapp.

Settheplotdimensions.

Exampleserver.rfilefromtutorial“HelloShiny2!”(the“underthehood”computa+ons)

Nameofplotstatedintheui.rfile,or“airPlot”.

NOTE:thiscolorgivestransparentcoloringforpoints.

Page 14: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

> runApp("hello_shiny_2", display.mode="showcase")

IncludingRcodeinwebapp

Theviewabletabslettheusertogglebetweentheui.Randserver.Rsourcefiles.

Page 15: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Drop-downlists(i.e.selectInput)

•  Here,wewillallowtheusertocolorthepointsinanX-Ysca<erplotbasedona3rdfactorvariable.

•  Wewillalsousethesame3rdfactorvariabletodesignatetheshapeofthepoint.

•  Wewillcarryforwardthesliderforchoosingthepointsizeofthepointsaswell.

> runApp("hello_shiny_3")

Page 16: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Webaccessibleversion:h<p://shiny.rhondadecook.com/hello_shiny_3/

Page 17: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

library(shiny)library(car) ## To get access to ‘Soils’ data set.

shinyUI(fluidPage(titlePanel("Hello Shiny 3!"),sidebarLayout(

sidebarPanel(sliderInput("size", "Point size:",

min=0.5, max=4, value=2),selectInput("chosen", label="Color/Shape

Factor", choices = c("Group","Contour","Depth"), selected="Contour", multiple = FALSE)

),mainPanel(

plotOutput("soilPlot"))

)))

Exampleui.rfilefromtutorial“HelloShiny3!”(seRng-upthestructureofthewebpage)

Putthesliderforinputsoverinthesidebarpanel.

Createalayoutwithasidebar(1/3space)andmainarea(2/3space).

Putthegeneratedplotinthemainpanel.

Giveyouroutputplotaname,suchas“soilPlot”.Thisnamewillalsobeusedintheserver.rfile.

Putthedrop-downchoices(selectInput)forinputsinthesidebarpanel,definechoices,andsetadefaultchoice.

Page 18: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

library(shiny)library(car) ## To get access to ‘Soils’ data set.

shinyServer(function(input,output){output$soilPlot<-renderPlot({

## The chosen color/shape factor data:pchInput<-Soils[,input$chosen]x<-Soils$pHy<-Soils$Dens## Choose enough colors for max levels of any plotting factor:colorVec<-colors()[c(490,450,81,52,67,83,84,47,142,121,373,530)]## Create your numeric identifier for color/shape:numericInput<-as.numeric(pchInput)## Assign each observation the appropriate color:colorForPoints<-colorVec[numericInput]plot(x,y,col=colorForPoints,pch=numericInput,xlab="pH",

ylab="Density",cex.lab=1.5,cex=input$size) legend("bottomright",levels(pchInput),col=colorVec,

pch=sort(unique(numericInput)))}, height = 500, width = 500)

})

Generatetheplotbasedonuser-inputs“chosen”and“size”fromwebapp.

Settheplotdimensions.

Exampleserver.rfilefromtutorial“HelloShiny3!”(the“underthehood”computa+ons)

Nameofplotstatedintheui.rfile,or“soilPlot”.

Setuser-definedinputcolor/shapeinplot(theseareallfactorsinSoils).

Page 19: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

## As part of sidebar in the earlier ui.R file…

shinyUI(fluidPage(sidebarLayout(

sidebarPanel(sliderInput(<stuff>),selectInput(<stuff>),br(),p(strong("Data Set Info:"), "From",

code("car"), "library."),p("Measured soil characteristics

from 48 samples.")),mainPanel(

plotOutput("soilPlot"))

)))

ProvidingextrahelptextinyourShinyapp,usetheui.rfile.(Ifyouwanttoincludeinforma+onfortheuser)

Newparagraph.Linebreak.

Boldfont.

Codingfont.

Page 20: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)
Page 21: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Rshinyprovides11specificexampleseachhighligh+ngacertainability:

Differentpagelayoutotherthansidebar/mainplotseRngrowsandcolumns:

> runExample()

Valid examples are "01_hello", "02_text", "03_reactivity", "04_mpg", "05_sliders", "06_tabsets", "07_widgets", "08_html", "09_upload", "10_download", "11_timer"

Afewotherop+ons

SeeRstudiowebsitegallery:h<ps://shiny.rstudio.com/gallery/

Page 22: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

tabsetPanel(…) andtabPanel(…) canbeusedtoallowmul+plepageswithinthesameapp.

mainPanel( tabsetPanel( tabPanel("Plot", plotOutput("plot")), tabPanel("Summary",

verbatimTextOutput("summary")), tabPanel("Table", tableOutput("table")) ) )

Afewotherop+ons

h<ps://shiny.rstudio.com/ar+cles/tabsets.html

Page 23: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

NOTE:YourRsessionwillbebusywhilerunningaShinyapp,soyouwillnotbeabletorunanyRcommandswhiletheShinyappisrunning.Rismonitoringtheappandexecu+ngtheapp’sreac+ons.

TogetyourRsessionback,hitescapeor,ifusingRStudio,clickthestopsignicon(foundintheupperrightcorneroftheRStudioconsolepanel).

> runExample("01_hello")

Listening on http://128.255.147.7

Exi+ngyourShinyapp

Page 24: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

<folder,directorypath>

my_app

ui.R

server.R

Ifyouhaveadatafiletobeusedfortheshinyapp,putitintheappfolder.Toreadthedata,wewillincludetheread.csv() commandinafilecalledglobal.R,whichwillalsobeintheappfolder.Shinyautoma+callyknowstorunglobal.Ronceuponlaunchoftheapp.Seethenextslideforaglobal.R examplefile.

Folder/FilestructureforRshinyappifyouhaveadatasettoread-inand/ormanipulatepriortouse.

global.R

somedata.csv

Page 25: An Introduc+on to R Shiny - University of Iowahomepage.stat.uiowa.edu/~rdecook/stat6220/Class_notes/R-shiny...An Introduc+on to R Shiny (shiny is an R package by R Studio)

Anexampleofaglobal.R filedata <- read.csv("somedata.csv")

library(plyr) ## For mapvalues() function below.

## Original factor levels were not in right order:data$nPeople<-mapvalues(data$nPeople,

from=levels(data$nPeople),to=c("1","2","3","4","5","6","7", "8", "9","10","15+"))

## Change var type of numerically coded factors:data$Subject <- as.factor(data$Subject)

## Define global variables:factnames <- names( Filter( is.factor, data ) ) numnames <- names( Filter( is.numeric, data ) )

Aaerlaunchingtheapp,boththeui.R and server.Rwillhaveaccesstotheobject‘data’andanyoftheglobalvariablesthatweredefinedhere.NOTE:itispossibletoincludetheread.csv() commandatthetopoftheui.R and server.Rfiles,butIfindusingtheglobal.Rfilebe<erprac+ce.