• Awebapplica+onframeworkforR
• RShinymakesitveryeasytobuildinterac+vewebapplica+onswithR
• Muchofthisintroductoryinforma+onistakendirectlyfromtheavailabletutorialfromRStudio– h<p://shiny.rstudio.com/tutorial/
AnIntroduc+ontoRShiny(shinyisanRpackagebyRStudio)
Tutorial“HelloShiny!”OpenRandrunthetutorialexample
> library(shiny)> runExample("01_hello")
• 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
Let’stakeacloselookatthesetwofilesforthe“HelloShiny!”app
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.
Set-upargumentsforthehist()func+onbasedonuser-input“bins”fromwebapp.
Generatethehist()plotwithgivenarguments.
Exampleserver.r filefromtutorial“HelloShiny!”(the“underthehood”computa+ons)
Nameofoutputplotstatedintheui.rfile,or“distPlot”.
<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
RunninganRShinyApp• EveryShinyapphasthesamestructure:– twoRscriptssavedtogetherinadirectory.Ataminimum,aShinyapphasui.Randserver.Rfiles.
• YoucancreateaShinyappbymakinganewfiledirectoryandsavingaui.Randserver.Rfileinsideit.Eachappwillneeditsownuniquedirectory(orfolder).
• YoucanrunaShinyappbygivingthenameofitsdirectorytothefunc+onrunApp().
> library(shiny)> runApp("my_app")
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")
MynewRShinyapp
• Airqualitysca<erplot:Ozonevs.Wind– Inputslider:sizeofpoints
> setwd("Stat_6220/R-shiny")> library(shiny)> runApp("hello_shiny_2")
Choosingsmallpoints.
Choosinglargepoints.
Webaccessibleversion:h<p://shiny.rhondadecook.com/hello_shiny_2/
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.
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.
> runApp("hello_shiny_2", display.mode="showcase")
IncludingRcodeinwebapp
Theviewabletabslettheusertogglebetweentheui.Randserver.Rsourcefiles.
Drop-downlists(i.e.selectInput)
• Here,wewillallowtheusertocolorthepointsinanX-Ysca<erplotbasedona3rdfactorvariable.
• Wewillalsousethesame3rdfactorvariabletodesignatetheshapeofthepoint.
• Wewillcarryforwardthesliderforchoosingthepointsizeofthepointsaswell.
> runApp("hello_shiny_3")
Webaccessibleversion:h<p://shiny.rhondadecook.com/hello_shiny_3/
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.
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).
## 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.
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/
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
NOTE:YourRsessionwillbebusywhilerunningaShinyapp,soyouwillnotbeabletorunanyRcommandswhiletheShinyappisrunning.Rismonitoringtheappandexecu+ngtheapp’sreac+ons.
TogetyourRsessionback,hitescapeor,ifusingRStudio,clickthestopsignicon(foundintheupperrightcorneroftheRStudioconsolepanel).
> runExample("01_hello")
Listening on http://128.255.147.7
Exi+ngyourShinyapp
<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
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.