SlideShare une entreprise Scribd logo
1  sur  109
Télécharger pour lire hors ligne
DataSciencewithR(DataAnalytics)
Introduc on to Shiny
Copyright NYC Data Science Academy, Supstat Inc. | All rights reserved
Outline
Part 1 : Shiny introduction
Part 2 : Design the User-interface
·
Structure of a Shiny App
Running an App
-
-
·
Layout
HTML Content
Headers
Formatted text
Images
-
-
-
-
-
Part 3 : Control Widgets
Part 4 : Build reactive output
Part 5 : Use datatable in Shiny Apps
·
Adding widgets-
·
Add R objects to ui.R
Build the object in server.R
render* function
-
-
-
·
2/110
Part1: Shiny introduction
3/110
What is Shiny?
A web application framework for R
Turn your analyses into interactive web applications
NO HTML, CSS, or JavaScript knowledge required
·
·
·
4/110
Shiny features
Shiny makes it super simple for R users to turn analyses into interactive web applications
that anyone can use.
Let your users choose input parameters using friendly controls like sliders, drop-downs,
and text fields.
Easily incorporate any number of outputs like plots, tables, and summaries.
If you have some experience with R, you're just minutes away from combining the statistical
power of R with the simplicity of a web page.
·
·
·
·
5/110
Example 1 : Hello shiny!
library(shiny)
runExample("01_hello")
6/110
Example 2
7/110
Example 3
8/110
Structure of a Shiny App
9/110
Structure of a Shiny App
Shiny apps have two components:
A user-interface script
A server script
·
Store in ui.Rscript
Control the layout and appearance
-
-
·
Store in server.Rscript
Instructions computer needs to build app
-
-
10/110
Structure of a Shiny App
User-interface script
Here is the ui.Rscript for the Hello Shinyexample.
Defined in a source script named ui.R
Controls the layout and appearance of your app
·
·
11/110
ui.R
shinyUI(fluidPage(
#Applicationtitle
titlePanel("HelloShiny!"),
#Sidebarwithasliderinputforthenumberofbins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Numberofbins:",
min=1,
max=50,
value=30)
),
#Showaplotofthegenerateddistribution
mainPanel(
plotOutput("distPlot")
)
)
))
12/110
Structure of a Shiny App
Server script
Here is the server.Rscript for the Hello Shinyexample.
Defined in a source script named server.R.
Contains instructions that your computer needs to build your app.
·
·
13/110
server.R
shinyServer(function(input,output){
#Expressionthatgeneratesahistogram.Theexpressionis
#wrappedinacalltorenderPlottoindicatethat:
#
# 1)Itis"reactive"andthereforeshouldre-executeautomatically
# wheninputschange
# 2)Itsoutputtypeisaplot
output$distPlot<-renderPlot({
x <-faithful[,2] #OldFaithfulGeyserdata
bins<-seq(min(x),max(x),length.out=input$bins+1)
#drawthehistogramwiththespecifiednumberofbins
hist(x,breaks=bins,col='darkgray',border='white')
})
})
14/110
Running an App
15/110
Running an App
Every Shiny app has the same structure: two R scripts saved together in a directory.·
At a minimum, a Shiny app has ui.Rand server.Rfiles.-
16/110
Running an App
Create a Shiny app by making a new directory and saving a ui.Rand server.Rfile inside it.
Each app will need its own unique directory.
·
·
17/110
Running an App
If your Shiny app is in a directory called my_app, run it with the following code:
The first argument of runAppis the app’s directory.
Run a Shiny app by giving the name of its directory to the function runApp.
For example :
·
·
library(shiny)
runApp("~/my_app")
18/110
Running an App
More examples without coding
library(shiny)
runExample("01_hello")#ahistogram
runExample("02_text")#tablesanddataframes
runExample("03_reactivity")#areactiveexpression
runExample("04_mpg")#globalvariables
runExample("05_sliders")#sliderbars
runExample("06_tabsets")#tabbedpanels
runExample("07_widgets")#helptextandsubmitbuttons
...
19/110
Part2: Design the User-interface
20/110
Create an empty App
ui.R
server.R
Edit the scripts to match the ones below:·
shinyUI(fluidPage(
))
shinyServer(function(input,output){
})
This code is the bare minimum needed to create a Shiny app.
The result is an empty app with a blank user-interface, an appropriate starting point for this
lesson.
·
·
21/110
Layout
22/110
Layout
ui.Rscripts use the function fluidPageto create a display that automatically adjusts to the
dimensions of your user’s browser window.
Lay out your app by placing elements in the function fluidPage.
·
·
#ui.R
shinyUI(fluidPage(
titlePanel("titlepanel"),
sidebarLayout(
sidebarPanel("sidebarpanel"),
mainPanel("mainpanel")
)
))
23/110
Layout
It creates a UI with 3 titles:·
24/110
Layout
Add elements to fluidPage
titlePaneland sidebarLayout·
The two most popular elements to add to fluidPage.
Create a basic Shiny app with a sidebar.
-
-
25/110
Layout
titlePanelshow the head title.
sidebarLayoutalways takes two arguments:
·
·
sidebarPanelfunction output
mainPanelfunction output
-
default:left-
-
#ui.R
shinyUI(fluidPage(
titlePanel("titlepanel"),
##Title oftheshiny.
sidebarLayout(
sidebarPanel("sidebarpanel"),##SideBarpaneltitle
mainPanel("mainpanel") ##Mainpaneltitle
)
))
26/110
Layout
Switch sidebar Panel to right
Add argument:position="right"·
shinyUI(fluidPage(
titlePanel("titlepanel"),
sidebarLayout(position="right",
sidebarPanel("sidebarpanel"),
mainPanel("mainpanel")
)
))
27/110
Layout
Switch sidebar Panel to right
Add argument:position="right"·
28/110
Layout
More layout design
Grid Layout
Tabsets
Navlists
Navbar Pages
etc. http://shiny.rstudio.com/articles/layout-guide.html
(http://shiny.rstudio.com/articles/layout-guide.html)
·
·
·
·
·
29/110
HTML Content
30/110
HTML Content
Add content to your Shiny app by placing it inside a *Panelfunction.
For example:
e.g sidebarPanel("sidebar panel").
·
·
Add the character string to the sidebarPanelfunction,-
#ui.R
shinyUI(fluidPage(
titlePanel("titlepanel"),
sidebarLayout(
sidebarPanel("sidebarpanel"),
mainPanel("mainpanel")
)
))
31/110
HTML Content
Function for HTML5
SHINY FUNCTION HTML5 CREATES
p <p> A paragraph of text
h1 <h1> A first level header
h2 <h2> A second level header
... ... ...
h6 <h6> A sixth level header
a <a> A hyper link
Use one of Shiny’s HTML tag functions to add more advanced content.
These functions parallel common HTML5 tags.
·
·
32/110
HTML Content
Function for HTML5
SHINY FUNCTION HTML5 CREATES
br <br> A line break (e.g. a blank line)
div <div> A division of text with a uniform style
span <span> An in‐line division of text with a uniform style
pre <pre> Text ‘as is’ in a fixed width font
code <code> A formatted block of code
img <img> An image
strong <strong> Bold text
em <em> Italicized text
33/110
Headers
34/110
Headers
To create a header element:
my title
Select a header function (e.g., h1or h5)
Give it the text you want to see in the header
·
·
library(shiny)
h1("mytitle")
35/110
Headers
Pass the argument h1("my title")to titlePanel, sidebarPanel, or mainPanel
Put the code in your ui.Rand runApp().
·
·
#ui.R
shinyUI(fluidPage(
titlePanel("MyShinyApp"),
sidebarLayout(
sidebarPanel(),
mainPanel(
h1("Firstleveltitle"),
h2("Secondleveltitle"),
h3("Thirdleveltitle"),
h4("Fourthleveltitle"),
h5("Fifthleveltitle"),
h6("Sixthleveltitle")
)
)
))
36/110
Headers
37/110
Headers
My Title
h3 title in the center.
align = "center"can be used to make the title place center·
h2("MyTitle",align="center")
h3("h3titleinthecenter.",align="center")
38/110
Headers : Example
align = "center"can be used to make the title place center.
Put the code in your ui.Rand runApp().·
#ui.R
shinyUI(fluidPage(
titlePanel("MyShinyApp"),
sidebarLayout(
sidebarPanel(),
mainPanel(
h1("Firstleveltitle",align="center"),
h2("Secondleveltitle",align="center"),
h3("Thirdleveltitle",align="center"),
h4("Fourthleveltitle",align="center"),
h5("Fifthleveltitle",align="center"),
h6("Sixthleveltitle",align="center")
)
)
))
39/110
Headers : Example
- align="center"
40/110
Formatted text
41/110
Formatted text
Maybe you want:
Time to use other functions
·
some content bold
Need a line break
Put script into special type
Different color
-
-
-
-
42/110
Formatted text
Put the code in your ui.Rand runApp().·
shinyUI(fluidPage(
titlePanel("MyShinyApp"),
sidebarLayout(sidebarPanel(),
mainPanel(
p("pcreatesaparagraphoftext.Note:thisparagraphisfollowedbybr(),
whichmakesablankline."),
p("Anewp()commandstartsanewparagraph.Supplyastyleattributetochange
theformatoftheentireparagraph",
style="font-family:'times';font-si16pt"),
strong("strong()makesboldtext."),
em("em()createsitalicized(i.e,emphasized)text."),
br(),
43/110
Formatted text
Put the code in your ui.Rand runApp().·
code("codedisplaysyourtextsimilartocomputercode"),
div("divcreatessegmentsoftextwithasimilarstyle.Thisdivisionoftext
isallbluebecauseIpassedtheargument'style=color:blue'todiv",
style="color:blue"),
br(),
p("spandoesthesamethingasdiv,butitworkswith",
span("groupsofwords",style="color:blue"),
"thatappearinsideaparagraph.")
)
)
))
44/110
Formatted text
Put the code in your ui.Rand runApp().·
45/110
Images
46/110
Images
Put a image in UI
Download an image from here:
Use the function img()
·
·
http://shiny.rstudio.com/tutorial/lesson2/www/bigorb.png
(http://shiny.rstudio.com/tutorial/lesson2/www/bigorb.png)
-
·
47/110
Images
To insert an image, give the img()function the name of your image file as the srcargument·
img(src="my_image.png")
Must spell out this argument since imgpasses your input to an HTML tag, and srcis what
the tag expects.
Change the size by:
·
·
img(src="my_image.png",height=72,width=72)
48/110
Images
The image must be in a folder named wwwin the same directory as the ui.Rscript.
Put the image into folder www
So if you want to use an image named bigorb.png, your wwwdirectory should look like this
one:
·
·
49/110
Images
Put images into *Panel
Put the code in your ui.Rand runApp().·
#ui.R
shinyUI(fluidPage(
titlePanel("MyShinyApp"),
sidebarLayout(
sidebarPanel(),
mainPanel(
img(src="bigorb.png",height=400,width=400)
)
)
))
50/110
Images
51/110
Summary
In this section we've learned·
How to build a ui.R.
How to add different titles.
How to write different types of content.
How to add an image to your UI.
-
-
-
-
52/110
Paart 3 : Control Widgets
53/110
What's a widget?
A web element that users can interact with.
Shiny widgets collect a value from user.
These widgets come from the Twitter Bootstrap (http://getbootstrap.com/2.3.2/) project, a
popular open source framework for building user-interfaces.
·
Widgets provide a way for users to send messages to the Shiny app.-
·
When a user changes the widget, the value will change as well.-
·
54/110
The standard Shiny widgets
FUNCTION WIDGET
actionButton Action Button
checkboxGroupInput A group of check boxes
checkboxInput A single check box
dateInput A calendar to aid date selection
dateRangeInput A pair of calendars for selecting a date range
fileInput A file upload control wizard
helpText Help text that can be added to an input form
numericInput A field to enter numbers
radioButtons A set of radio buttons
selectInput A box with choices to select from
sliderInput A slider bar
submitButton A submit button
textInput A field to enter text
55/110
The widget mentioned above
Buttons
Action
Submit
Single checkbox
Choice A
Checkbox group
Choice 1
Choice 2
Choice 3
Date input
2014-01-01
Date range
2015-09-15 to
2015-09-15
File input
No file chosenChoose File
Help text
Note: help text isn't a true widget,
but it provides an easy way to
add text to accompany other
widgets.
Numeric input
1
Radio buttons
Choice 1
Choice 2
Select box Sliders Text input
Enter text...
Basic widgets
0 10050
0 10025 75
Choice 1
shinyapps.io Powered by  
56/110
Adding widgets
Add a widget to your app
Each widget function requires several arguments.
A namefor the widget.
label.
·
place a widget function in sidebarPanelor mainPanelin your ui.Rfile.-
·
The first two arguments for each widget are:-
57/110
Adding widgets
Example : actionButton
actionButton(inputId,label,icon=NULL,...)
inputId:
label:
icon:
·
Specifies the input slot that will be used to access the value.-
·
The contents of the button or link-usually a text label, but you could also use any other
HTML, like an image.
-
·
An optional icon to appear on the button-
58/110
ActionButton
TouchToRun
Adding widgets
Example : actionButton
Action Button may look like this:·
sidebarPanel(h3("ActionButton"),
actionButton(1,"TouchToRun")
)
59/110
Adding widgets
Example : checkboxGroupInput
checkboxGroupInput(inputId,label,choices,selected=NULL)
inputId:
label:
choices:
selected: The values that should be initially selected, if any.
·
Input variable to assign the control's value to.-
·
Display label for the control.-
·
List of values to show checkboxes for. If elements of the list are named then that name
rather than the value is displayed to the user.
-
·
60/110
Checkbox group
Choice 1
Choice 2
Choice 3
Adding widgets
Example : checkboxGroupInput
Checkbox Group Input may look as this:·
sidebarPanel(checkboxGroupInput("checkGroup",
label=h3("Checkboxgroup"),
choices=list("Choice1"=1,
"Choice2"=2,
"Choice3"=3),selected=1))
61/110
Adding widgets
Example : checkboxInput
checkboxInput(inputId,label,value=FALSE)
inputId
label
value
·
Input variable to assign the control's value to.-
·
Display label for the control.-
·
Initial value (TRUE or FALSE).-
62/110
Check Box Input
Choice A
Adding widgets
Example : checkboxInput
Checkbox Input may look as this:·
checkboxInput("checkbox",label="ChoiceA",value=TRUE)
63/110
Adding widgets
Example : dateInput
dateInput(inputId,label,value=NULL,min=NULL,max=NULL,
format="yyyy-mm-dd",startview="month",weekstart=0,
language="en")
value:
min/max:
format:
·
The starting date. Either a Date object, or a string in yyyy-mm-dd format.-
·
The minimum/maximum allowed date. Either a Date object, or a string in yyyy-mm-dd
format.
-
·
The format of the date to display in the browser. Defaults: "yyyy-mm-dd".-
64/110
Adding widgets
Example : dateInput
dateInput(inputId,label,value=NULL,min=NULL,max=NULL,
format="yyyy-mm-dd",startview="month",weekstart=0,
language="en")
startview:
weekstart:
language:
·
The date range shown when the input object is first clicked. "month" , "year", or
"decade".
-
·
Which day is the start of the week.-
·
The language used for month and day names.-
65/110
Date input
Adding widgets
Example : dataInput
dateInput("date",
label=h3("Dateinput"),
value="2014-01-01")
66/110
Adding widgets
Example : dateRangeInput
dateRangeInput(inputId,label,start=NULL,end=NULL,separator="to",...)
start:
end:
separator:
args are same as dateInput
·
The initial start date. Either a Date object, or a string in yyyy-mm-dd format.-
·
The initial end date. Either a Date object, or a string in yyyy-mm-dd format.-
·
String to display between the start and end input boxes.-
·
67/110
Date range
to
Adding widgets
Example : dateRangeInput
dateRangeInput("dates",label=h3("Daterange"))
68/110
Adding widgets
Example : leInput
fileInput(inputId,label,multiple=FALSE,accept=NULL)
multiple:
accept:
·
Whether the user should be allowed to select and upload multiple files at once.-
·
A character vector of MIME types; gives the browser a hint of what kind of files the server
is expecting.
-
69/110
File input
No file chosenChoose File
Adding widgets
Example : leInput
fileInput("file",label=h3("Fileinput"))
70/110
Adding widgets
Example : helpText
helpText(...)
· One or more help text strings (or other inline HTML elements)-
71/110
Help text
Note: help text isn't a
true widget, but it
provides an easy way
to add text to
accompany other
widgets.
Adding widgets
Example : helpText
sidebarPanel(
h3("Helptext"),
helpText("Note:helptextisn'tatruewidget,",
"butitprovidesaneasywaytoaddtextto",
"accompanyotherwidgets."))
72/110
Adding widgets
Example : numericInput
numericInput(inputId,label,value,min=NA,max=NA,step=NA)
value:
min:
max:
step:
·
Initial value-
·
Minimum allowed value-
·
Maximum allowed value-
·
Interval to use when stepping between min and max-
73/110
Numeric input
1
Adding widgets
Example : numericInput
numericInput("num",
label=h3("Numericinput"),
value=1)
74/110
Adding widgets
Example : radioButtons
radioButtons(inputId,label,choices,selected=NULL)
choices:
selected:
·
List of values to select from (if elements of the list are named then that name rather than
the value is displayed to the user)
-
·
The initially selected value (if not specified then defaults to the first value)-
75/110
Radio buttons
Choice 1
Choice 2
Choice 3
Adding widgets
Example : radioButtons
radioButtons("radio",label=h3("Radiobuttons"),
choices=list("Choice1"=1,"Choice2"=2,
"Choice3"=3),selected=1)
76/110
Adding widgets
Example : selectInput
selectInput(inputId,label,choices,selected=NULL,multiple=FALSE,
selectize=TRUE,...)
choices:
selected:
multiple:
selectize:
·
List of values to select from.-
·
The initially selected value (or multiple values if multiple = TRUE).-
·
Is selection of multiple items allowed?-
·
Whether to use selectize.js or not-
77/110
Select box
Choice 1
Adding widgets
Example : selectInput
selectInput("select",label=h3("Selectbox"),
choices=list("Choice1"=1,"Choice2"=2,
"Choice3"=3),selected=1)
78/110
Adding widgets
Example : sliderInput
sliderInput(inputId,label,min,max,value,step=NULL,round=FALSE,...)
min/max:
value:
step:
round:
·
The minimum/maximum value (inclusive) that can be selected.-
·
The initial value of the slider.-
·
Specifies the interval between each selectable value on the slider (NULL means no
restriction).
-
·
TRUE to round all values to the nearest integer; FALSE if no rounding is desired; or an
integer to round to that number of digits .
-
79/110
Sliderbar
Adding widgets
Example : sliderInput
sidebarPanel(
sliderInput("obs","",0,1000,0)
)
80/110
Adding widgets
Example : submitButton
submitButton(text="ApplyChanges",icon=NULL,...)
text:
icon:
·
Button caption-
·
Optional icon to appear on the button-
81/110
SubmitButton
Submit
Adding widgets
Example : submitButton
submitButton("Submit")
82/110
Adding widgets
Example : textInput
textInput(inputId,label,value="",...)
inputId:
label:
value:
·
Input variable to assign the control's value to-
·
Display label for the control-
·
Initial value-
83/110
Text input
Enter text...
Adding widgets
Example : textInput
textInput("text",label=h3("Textinput"),
value="Entertext...")
84/110
Part 4 : Build reactive output
85/110
Preparation
Create a folder in your working directory named new_app.
Save the ui.Rand server.Rfiles that you make in this section in new_app.
·
·
86/110
Two steps
You can create reactive output with a two step process.
1. Add an R object to your user-interface with ui.R.
2. Tell Shiny how to build the object in server.R.
The object will be reactive if the code that builds it calls a widget value.
87/110
Create UI
There are several output functions for creating di erent type of outputs.
OUTPUT FUNCTION CREATES
htmlOutput raw HTML
imageOutput image
plotOutput plot
tableOutput table
textOutput text
uiOutput raw HTML
verbatimTextOutput text
Place the output function inside sidebarPanelor mainPanelin the ui.Rscript.·
88/110
Add R objects to ui.R
Example for ui.R
Use helpText, selectInput, sideInputto input values·
shinyUI(fluidPage(
titlePanel("RATEME!"),
sidebarLayout(
sidebarPanel(
helpText("Whatdoyouthinkaboutthisapp?"),
selectInput("var",
label="Chooseonetodisplay",
choices=c("awesome","dramastic",
"admirable","wonderful"),
selected="awesome"),
sliderInput("range",
label="Persents:",
min=90,max=100,value=100)
),
89/110
Add R objects to ui.R
Example for ui.R
mainPanel(
textOutput("text1")
)
)
))
Use textOutputin mailPanel to show where to place the output.
Each of the *Outputfunctions require a single argument:
a character string that Shiny will use as the name of your reactive element.
Your users will not see this name, but you will use it later.
·
·
·
90/110
Show the UI
What do you think about this app?
Choose one to display
Persents:
RATE ME!
90 100
awesome
shinyapps.io Powered by  
91/110
Build the object in server.R
Placing a function *Outputin ui.Rtells Shiny where to display your object.
Provide R code to build the object in server.R.
Place the R code in the unnamed functionthat appears inside shinyServerin your
server.Rscript.
·
·
·
92/110
Build the object in server.R
Code in the unnamed function that appears inside shinyServer·
#server.R
shinyServer(function(input,output){
output$text1<-renderText({
"Youhaveselectedthis"
})
}
)
93/110
Build the object in server.R
Make sure the element name match the name of the reactive element that you created in
ui.R.
e.g. output$text1matches textOutput("text1")in ui.Rscript.
·
#server.R
shinyServer(function(input,output){
output$text1<-renderText({
"Youhaveselectedthis"
})
}
)
94/110
render*function
RENDER FUNCTION CREATES
renderImage images (saved as a link to a source file)
renderPlot plots
renderPrint any printed output
renderTable data frame, matrix, other table like structures
renderText character strings
renderUI a Shiny tag object or HTML
Each entry to output should contain the output of one of Shiny’s render*functions.·
Each render*function takes a single argument:
an R expression surrounded by braces, {}.
·
Instructions that you give Shiny to store.-
95/110
Make your text reactive
Use Inputand Outputin ui.R
Make your text reactive by asking Shiny to call a widget value.·
Outputstores instructions for building the R objects in your app.
Inputstores the current values of all of the widgets in your app.
·
·
96/110
Make your text reactive
Example : build a reactive text
Assumed our app has two widgets: varand range.
#server.R
shinyServer(function(input,output){
output$text1<-renderText({
paste("Thisappis",input$range,"%",input$var,"!!!")
})
}
)
97/110
Show it
Use runApp()to show your app
What do you think about this app?
Choose one to display
Persents:
RATE ME!
90 100
awesome
shinyapps.io Powered by  
98/110
Part 5 : Use datatable in Shiny Apps
99/110
Use datatable in Shiny Apps
renderDataTable()
The DataTables application demonstrates HTML tables using the jQuery library DataTables.
The basic usage:
To create an output element in the UI using
·
·
·
dataTableOutput(id='foo')`
Render a table on the server side using·
output$foo<-renderDataTable({data}).
100/110
A simple example for renderDataTable
The script is as follows:
(It's so simple that you don't need to create ui.R,server.R)
·
runApp(list(
ui=basicPage(
h2('Themtcarsdata'),
dataTableOutput('mytable')
),
server=function(input,output){
output$mytable=renderDataTable({
mtcars
})
}
))
101/110
A simple example for renderDataTable
Show it
102/110
A complete example for renderDataTable
Script of ui.R:
A shiny including three datasets: mtcars,iris,diamonds.
#ui.R
library(shiny)
library(ggplot2) #forthediamondsdataset
shinyUI(pageWithSidebar(
headerPanel('ExamplesofDataTables'),
sidebarPanel(
checkboxGroupInput('show_vars','Columnsindiamondstoshow:',names(diamonds),
selected=names(diamonds)),
103/110
A complete example for renderDataTable
Script of ui.R
helpText('Forthediamondsdata,wecanselectvariablestoshowinthetable;
forthemtcarsexample,weusebSortClasses=TRUEsothatsorted
columnsarecoloredsincetheyhavespecialCSSclassesattached;
fortheirisdata,wecustomizethelengthmenusowecandisplay5
rowsperpage.')
),
mainPanel(
tabsetPanel(
tabPanel('diamonds',
dataTableOutput("mytable1")),
tabPanel('mtcars',
dataTableOutput("mytable2")),
tabPanel('iris',
dataTableOutput("mytable3"))
)
)
))
104/110
renderDataTable
w_vars
ALSE]
seCSSareattachedtothem
display5rowsperpagebydefault
50),iDisplayLength=5))
106/110
A complete example for renderDataTable
108/110
A complete example for renderDataTable
109/110
Summary
In this section, you created your first reactive Shiny app. Including:·
use an *Outputfunction in the ui.Rscript to place reactive objects in your Shiny app.
use a render*function in the server.R script to tell Shiny how to build your objects.
surround R expressions by braces, {}, in each render*function.
save your render*expressions in the output list, with one entry for each reactive object
in your app.
create reactivity by including an inputvalue in a render*expression.
-
-
-
-
-
110/110

Contenu connexe

En vedette

Max Kuhn's talk on R machine learning
Max Kuhn's talk on R machine learningMax Kuhn's talk on R machine learning
Max Kuhn's talk on R machine learningVivian S. Zhang
 
Kaggle Top1% Solution: Predicting Housing Prices in Moscow
Kaggle Top1% Solution: Predicting Housing Prices in Moscow Kaggle Top1% Solution: Predicting Housing Prices in Moscow
Kaggle Top1% Solution: Predicting Housing Prices in Moscow Vivian S. Zhang
 
Data mining with caret package
Data mining with caret packageData mining with caret package
Data mining with caret packageVivian S. Zhang
 
Winning data science competitions, presented by Owen Zhang
Winning data science competitions, presented by Owen ZhangWinning data science competitions, presented by Owen Zhang
Winning data science competitions, presented by Owen ZhangVivian S. Zhang
 
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its authorKaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its authorVivian S. Zhang
 
Tips for data science competitions
Tips for data science competitionsTips for data science competitions
Tips for data science competitionsOwen Zhang
 

En vedette (7)

Max Kuhn's talk on R machine learning
Max Kuhn's talk on R machine learningMax Kuhn's talk on R machine learning
Max Kuhn's talk on R machine learning
 
Kaggle Top1% Solution: Predicting Housing Prices in Moscow
Kaggle Top1% Solution: Predicting Housing Prices in Moscow Kaggle Top1% Solution: Predicting Housing Prices in Moscow
Kaggle Top1% Solution: Predicting Housing Prices in Moscow
 
Data mining with caret package
Data mining with caret packageData mining with caret package
Data mining with caret package
 
Winning data science competitions, presented by Owen Zhang
Winning data science competitions, presented by Owen ZhangWinning data science competitions, presented by Owen Zhang
Winning data science competitions, presented by Owen Zhang
 
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its authorKaggle Winning Solution Xgboost algorithm -- Let us learn from its author
Kaggle Winning Solution Xgboost algorithm -- Let us learn from its author
 
Xgboost
XgboostXgboost
Xgboost
 
Tips for data science competitions
Tips for data science competitionsTips for data science competitions
Tips for data science competitions
 

Plus de Vivian S. Zhang

Career services workshop- Roger Ren
Career services workshop- Roger RenCareer services workshop- Roger Ren
Career services workshop- Roger RenVivian S. Zhang
 
Nycdsa wordpress guide book
Nycdsa wordpress guide bookNycdsa wordpress guide book
Nycdsa wordpress guide bookVivian S. Zhang
 
Nyc open-data-2015-andvanced-sklearn-expanded
Nyc open-data-2015-andvanced-sklearn-expandedNyc open-data-2015-andvanced-sklearn-expanded
Nyc open-data-2015-andvanced-sklearn-expandedVivian S. Zhang
 
Nycdsa ml conference slides march 2015
Nycdsa ml conference slides march 2015 Nycdsa ml conference slides march 2015
Nycdsa ml conference slides march 2015 Vivian S. Zhang
 
THE HACK ON JERSEY CITY CONDO PRICES explore trends in public data
THE HACK ON JERSEY CITY CONDO PRICES explore trends in public dataTHE HACK ON JERSEY CITY CONDO PRICES explore trends in public data
THE HACK ON JERSEY CITY CONDO PRICES explore trends in public dataVivian S. Zhang
 
Natural Language Processing(SupStat Inc)
Natural Language Processing(SupStat Inc)Natural Language Processing(SupStat Inc)
Natural Language Processing(SupStat Inc)Vivian S. Zhang
 
Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...
Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...
Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...Vivian S. Zhang
 
Data Science Academy Student Demo day--Divyanka Sharma, Businesses in nyc
Data Science Academy Student Demo day--Divyanka Sharma, Businesses in nycData Science Academy Student Demo day--Divyanka Sharma, Businesses in nyc
Data Science Academy Student Demo day--Divyanka Sharma, Businesses in nycVivian S. Zhang
 
Data Science Academy Student Demo day--Chang Wang, dogs breeds in nyc
Data Science Academy Student Demo day--Chang Wang, dogs breeds in nycData Science Academy Student Demo day--Chang Wang, dogs breeds in nyc
Data Science Academy Student Demo day--Chang Wang, dogs breeds in nycVivian S. Zhang
 
Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...
Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...
Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...Vivian S. Zhang
 
Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...
Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...
Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...Vivian S. Zhang
 
Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...Vivian S. Zhang
 
Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...
Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...
Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...Vivian S. Zhang
 
R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...
R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...
R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...Vivian S. Zhang
 

Plus de Vivian S. Zhang (16)

Why NYC DSA.pdf
Why NYC DSA.pdfWhy NYC DSA.pdf
Why NYC DSA.pdf
 
Career services workshop- Roger Ren
Career services workshop- Roger RenCareer services workshop- Roger Ren
Career services workshop- Roger Ren
 
Nycdsa wordpress guide book
Nycdsa wordpress guide bookNycdsa wordpress guide book
Nycdsa wordpress guide book
 
Xgboost
XgboostXgboost
Xgboost
 
Nyc open-data-2015-andvanced-sklearn-expanded
Nyc open-data-2015-andvanced-sklearn-expandedNyc open-data-2015-andvanced-sklearn-expanded
Nyc open-data-2015-andvanced-sklearn-expanded
 
Nycdsa ml conference slides march 2015
Nycdsa ml conference slides march 2015 Nycdsa ml conference slides march 2015
Nycdsa ml conference slides march 2015
 
THE HACK ON JERSEY CITY CONDO PRICES explore trends in public data
THE HACK ON JERSEY CITY CONDO PRICES explore trends in public dataTHE HACK ON JERSEY CITY CONDO PRICES explore trends in public data
THE HACK ON JERSEY CITY CONDO PRICES explore trends in public data
 
Natural Language Processing(SupStat Inc)
Natural Language Processing(SupStat Inc)Natural Language Processing(SupStat Inc)
Natural Language Processing(SupStat Inc)
 
Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...
Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...
Data Science Academy Student Demo day--Moyi Dang, Visualizing global public c...
 
Data Science Academy Student Demo day--Divyanka Sharma, Businesses in nyc
Data Science Academy Student Demo day--Divyanka Sharma, Businesses in nycData Science Academy Student Demo day--Divyanka Sharma, Businesses in nyc
Data Science Academy Student Demo day--Divyanka Sharma, Businesses in nyc
 
Data Science Academy Student Demo day--Chang Wang, dogs breeds in nyc
Data Science Academy Student Demo day--Chang Wang, dogs breeds in nycData Science Academy Student Demo day--Chang Wang, dogs breeds in nyc
Data Science Academy Student Demo day--Chang Wang, dogs breeds in nyc
 
Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...
Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...
Data Science Academy Student Demo day--Richard Sheng, kinvolved school attend...
 
Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...
Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...
Data Science Academy Student Demo day--Peggy sobolewski,analyzing transporati...
 
Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...Data Science Academy Student Demo day--Michael blecher,the importance of clea...
Data Science Academy Student Demo day--Michael blecher,the importance of clea...
 
Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...
Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...
Data Science Academy Student Demo day--Shelby Ahern, An Exploration of Non-Mi...
 
R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...
R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...
R003 laila restaurant sanitation report(NYC Data Science Academy, Data Scienc...
 

Dernier

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxpboyjonauth
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon AUnboundStockton
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptxPoojaSen20
 

Dernier (20)

Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Introduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptxIntroduction to AI in Higher Education_draft.pptx
Introduction to AI in Higher Education_draft.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Crayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon ACrayon Activity Handout For the Crayon A
Crayon Activity Handout For the Crayon A
 
PSYCHIATRIC History collection FORMAT.pptx
PSYCHIATRIC   History collection FORMAT.pptxPSYCHIATRIC   History collection FORMAT.pptx
PSYCHIATRIC History collection FORMAT.pptx
 

Nyc data scienceacademy_shinyparti

  • 1. DataSciencewithR(DataAnalytics) Introduc on to Shiny Copyright NYC Data Science Academy, Supstat Inc. | All rights reserved
  • 2. Outline Part 1 : Shiny introduction Part 2 : Design the User-interface · Structure of a Shiny App Running an App - - · Layout HTML Content Headers Formatted text Images - - - - - Part 3 : Control Widgets Part 4 : Build reactive output Part 5 : Use datatable in Shiny Apps · Adding widgets- · Add R objects to ui.R Build the object in server.R render* function - - - · 2/110
  • 4. What is Shiny? A web application framework for R Turn your analyses into interactive web applications NO HTML, CSS, or JavaScript knowledge required · · · 4/110
  • 5. Shiny features Shiny makes it super simple for R users to turn analyses into interactive web applications that anyone can use. Let your users choose input parameters using friendly controls like sliders, drop-downs, and text fields. Easily incorporate any number of outputs like plots, tables, and summaries. If you have some experience with R, you're just minutes away from combining the statistical power of R with the simplicity of a web page. · · · · 5/110
  • 6. Example 1 : Hello shiny! library(shiny) runExample("01_hello") 6/110
  • 9. Structure of a Shiny App 9/110
  • 10. Structure of a Shiny App Shiny apps have two components: A user-interface script A server script · Store in ui.Rscript Control the layout and appearance - - · Store in server.Rscript Instructions computer needs to build app - - 10/110
  • 11. Structure of a Shiny App User-interface script Here is the ui.Rscript for the Hello Shinyexample. Defined in a source script named ui.R Controls the layout and appearance of your app · · 11/110
  • 13. Structure of a Shiny App Server script Here is the server.Rscript for the Hello Shinyexample. Defined in a source script named server.R. Contains instructions that your computer needs to build your app. · · 13/110
  • 14. server.R shinyServer(function(input,output){ #Expressionthatgeneratesahistogram.Theexpressionis #wrappedinacalltorenderPlottoindicatethat: # # 1)Itis"reactive"andthereforeshouldre-executeautomatically # wheninputschange # 2)Itsoutputtypeisaplot output$distPlot<-renderPlot({ x <-faithful[,2] #OldFaithfulGeyserdata bins<-seq(min(x),max(x),length.out=input$bins+1) #drawthehistogramwiththespecifiednumberofbins hist(x,breaks=bins,col='darkgray',border='white') }) }) 14/110
  • 16. Running an App Every Shiny app has the same structure: two R scripts saved together in a directory.· At a minimum, a Shiny app has ui.Rand server.Rfiles.- 16/110
  • 17. Running an App Create a Shiny app by making a new directory and saving a ui.Rand server.Rfile inside it. Each app will need its own unique directory. · · 17/110
  • 18. Running an App If your Shiny app is in a directory called my_app, run it with the following code: The first argument of runAppis the app’s directory. Run a Shiny app by giving the name of its directory to the function runApp. For example : · · library(shiny) runApp("~/my_app") 18/110
  • 19. Running an App More examples without coding library(shiny) runExample("01_hello")#ahistogram runExample("02_text")#tablesanddataframes runExample("03_reactivity")#areactiveexpression runExample("04_mpg")#globalvariables runExample("05_sliders")#sliderbars runExample("06_tabsets")#tabbedpanels runExample("07_widgets")#helptextandsubmitbuttons ... 19/110
  • 20. Part2: Design the User-interface 20/110
  • 21. Create an empty App ui.R server.R Edit the scripts to match the ones below:· shinyUI(fluidPage( )) shinyServer(function(input,output){ }) This code is the bare minimum needed to create a Shiny app. The result is an empty app with a blank user-interface, an appropriate starting point for this lesson. · · 21/110
  • 23. Layout ui.Rscripts use the function fluidPageto create a display that automatically adjusts to the dimensions of your user’s browser window. Lay out your app by placing elements in the function fluidPage. · · #ui.R shinyUI(fluidPage( titlePanel("titlepanel"), sidebarLayout( sidebarPanel("sidebarpanel"), mainPanel("mainpanel") ) )) 23/110
  • 24. Layout It creates a UI with 3 titles:· 24/110
  • 25. Layout Add elements to fluidPage titlePaneland sidebarLayout· The two most popular elements to add to fluidPage. Create a basic Shiny app with a sidebar. - - 25/110
  • 26. Layout titlePanelshow the head title. sidebarLayoutalways takes two arguments: · · sidebarPanelfunction output mainPanelfunction output - default:left- - #ui.R shinyUI(fluidPage( titlePanel("titlepanel"), ##Title oftheshiny. sidebarLayout( sidebarPanel("sidebarpanel"),##SideBarpaneltitle mainPanel("mainpanel") ##Mainpaneltitle ) )) 26/110
  • 27. Layout Switch sidebar Panel to right Add argument:position="right"· shinyUI(fluidPage( titlePanel("titlepanel"), sidebarLayout(position="right", sidebarPanel("sidebarpanel"), mainPanel("mainpanel") ) )) 27/110
  • 28. Layout Switch sidebar Panel to right Add argument:position="right"· 28/110
  • 29. Layout More layout design Grid Layout Tabsets Navlists Navbar Pages etc. http://shiny.rstudio.com/articles/layout-guide.html (http://shiny.rstudio.com/articles/layout-guide.html) · · · · · 29/110
  • 31. HTML Content Add content to your Shiny app by placing it inside a *Panelfunction. For example: e.g sidebarPanel("sidebar panel"). · · Add the character string to the sidebarPanelfunction,- #ui.R shinyUI(fluidPage( titlePanel("titlepanel"), sidebarLayout( sidebarPanel("sidebarpanel"), mainPanel("mainpanel") ) )) 31/110
  • 32. HTML Content Function for HTML5 SHINY FUNCTION HTML5 CREATES p <p> A paragraph of text h1 <h1> A first level header h2 <h2> A second level header ... ... ... h6 <h6> A sixth level header a <a> A hyper link Use one of Shiny’s HTML tag functions to add more advanced content. These functions parallel common HTML5 tags. · · 32/110
  • 33. HTML Content Function for HTML5 SHINY FUNCTION HTML5 CREATES br <br> A line break (e.g. a blank line) div <div> A division of text with a uniform style span <span> An in‐line division of text with a uniform style pre <pre> Text ‘as is’ in a fixed width font code <code> A formatted block of code img <img> An image strong <strong> Bold text em <em> Italicized text 33/110
  • 35. Headers To create a header element: my title Select a header function (e.g., h1or h5) Give it the text you want to see in the header · · library(shiny) h1("mytitle") 35/110
  • 36. Headers Pass the argument h1("my title")to titlePanel, sidebarPanel, or mainPanel Put the code in your ui.Rand runApp(). · · #ui.R shinyUI(fluidPage( titlePanel("MyShinyApp"), sidebarLayout( sidebarPanel(), mainPanel( h1("Firstleveltitle"), h2("Secondleveltitle"), h3("Thirdleveltitle"), h4("Fourthleveltitle"), h5("Fifthleveltitle"), h6("Sixthleveltitle") ) ) )) 36/110
  • 38. Headers My Title h3 title in the center. align = "center"can be used to make the title place center· h2("MyTitle",align="center") h3("h3titleinthecenter.",align="center") 38/110
  • 39. Headers : Example align = "center"can be used to make the title place center. Put the code in your ui.Rand runApp().· #ui.R shinyUI(fluidPage( titlePanel("MyShinyApp"), sidebarLayout( sidebarPanel(), mainPanel( h1("Firstleveltitle",align="center"), h2("Secondleveltitle",align="center"), h3("Thirdleveltitle",align="center"), h4("Fourthleveltitle",align="center"), h5("Fifthleveltitle",align="center"), h6("Sixthleveltitle",align="center") ) ) )) 39/110
  • 40. Headers : Example - align="center" 40/110
  • 42. Formatted text Maybe you want: Time to use other functions · some content bold Need a line break Put script into special type Different color - - - - 42/110
  • 43. Formatted text Put the code in your ui.Rand runApp().· shinyUI(fluidPage( titlePanel("MyShinyApp"), sidebarLayout(sidebarPanel(), mainPanel( p("pcreatesaparagraphoftext.Note:thisparagraphisfollowedbybr(), whichmakesablankline."), p("Anewp()commandstartsanewparagraph.Supplyastyleattributetochange theformatoftheentireparagraph", style="font-family:'times';font-si16pt"), strong("strong()makesboldtext."), em("em()createsitalicized(i.e,emphasized)text."), br(), 43/110
  • 44. Formatted text Put the code in your ui.Rand runApp().· code("codedisplaysyourtextsimilartocomputercode"), div("divcreatessegmentsoftextwithasimilarstyle.Thisdivisionoftext isallbluebecauseIpassedtheargument'style=color:blue'todiv", style="color:blue"), br(), p("spandoesthesamethingasdiv,butitworkswith", span("groupsofwords",style="color:blue"), "thatappearinsideaparagraph.") ) ) )) 44/110
  • 45. Formatted text Put the code in your ui.Rand runApp().· 45/110
  • 47. Images Put a image in UI Download an image from here: Use the function img() · · http://shiny.rstudio.com/tutorial/lesson2/www/bigorb.png (http://shiny.rstudio.com/tutorial/lesson2/www/bigorb.png) - · 47/110
  • 48. Images To insert an image, give the img()function the name of your image file as the srcargument· img(src="my_image.png") Must spell out this argument since imgpasses your input to an HTML tag, and srcis what the tag expects. Change the size by: · · img(src="my_image.png",height=72,width=72) 48/110
  • 49. Images The image must be in a folder named wwwin the same directory as the ui.Rscript. Put the image into folder www So if you want to use an image named bigorb.png, your wwwdirectory should look like this one: · · 49/110
  • 50. Images Put images into *Panel Put the code in your ui.Rand runApp().· #ui.R shinyUI(fluidPage( titlePanel("MyShinyApp"), sidebarLayout( sidebarPanel(), mainPanel( img(src="bigorb.png",height=400,width=400) ) ) )) 50/110
  • 52. Summary In this section we've learned· How to build a ui.R. How to add different titles. How to write different types of content. How to add an image to your UI. - - - - 52/110
  • 53. Paart 3 : Control Widgets 53/110
  • 54. What's a widget? A web element that users can interact with. Shiny widgets collect a value from user. These widgets come from the Twitter Bootstrap (http://getbootstrap.com/2.3.2/) project, a popular open source framework for building user-interfaces. · Widgets provide a way for users to send messages to the Shiny app.- · When a user changes the widget, the value will change as well.- · 54/110
  • 55. The standard Shiny widgets FUNCTION WIDGET actionButton Action Button checkboxGroupInput A group of check boxes checkboxInput A single check box dateInput A calendar to aid date selection dateRangeInput A pair of calendars for selecting a date range fileInput A file upload control wizard helpText Help text that can be added to an input form numericInput A field to enter numbers radioButtons A set of radio buttons selectInput A box with choices to select from sliderInput A slider bar submitButton A submit button textInput A field to enter text 55/110
  • 56. The widget mentioned above Buttons Action Submit Single checkbox Choice A Checkbox group Choice 1 Choice 2 Choice 3 Date input 2014-01-01 Date range 2015-09-15 to 2015-09-15 File input No file chosenChoose File Help text Note: help text isn't a true widget, but it provides an easy way to add text to accompany other widgets. Numeric input 1 Radio buttons Choice 1 Choice 2 Select box Sliders Text input Enter text... Basic widgets 0 10050 0 10025 75 Choice 1 shinyapps.io Powered by   56/110
  • 57. Adding widgets Add a widget to your app Each widget function requires several arguments. A namefor the widget. label. · place a widget function in sidebarPanelor mainPanelin your ui.Rfile.- · The first two arguments for each widget are:- 57/110
  • 58. Adding widgets Example : actionButton actionButton(inputId,label,icon=NULL,...) inputId: label: icon: · Specifies the input slot that will be used to access the value.- · The contents of the button or link-usually a text label, but you could also use any other HTML, like an image. - · An optional icon to appear on the button- 58/110
  • 59. ActionButton TouchToRun Adding widgets Example : actionButton Action Button may look like this:· sidebarPanel(h3("ActionButton"), actionButton(1,"TouchToRun") ) 59/110
  • 60. Adding widgets Example : checkboxGroupInput checkboxGroupInput(inputId,label,choices,selected=NULL) inputId: label: choices: selected: The values that should be initially selected, if any. · Input variable to assign the control's value to.- · Display label for the control.- · List of values to show checkboxes for. If elements of the list are named then that name rather than the value is displayed to the user. - · 60/110
  • 61. Checkbox group Choice 1 Choice 2 Choice 3 Adding widgets Example : checkboxGroupInput Checkbox Group Input may look as this:· sidebarPanel(checkboxGroupInput("checkGroup", label=h3("Checkboxgroup"), choices=list("Choice1"=1, "Choice2"=2, "Choice3"=3),selected=1)) 61/110
  • 62. Adding widgets Example : checkboxInput checkboxInput(inputId,label,value=FALSE) inputId label value · Input variable to assign the control's value to.- · Display label for the control.- · Initial value (TRUE or FALSE).- 62/110
  • 63. Check Box Input Choice A Adding widgets Example : checkboxInput Checkbox Input may look as this:· checkboxInput("checkbox",label="ChoiceA",value=TRUE) 63/110
  • 64. Adding widgets Example : dateInput dateInput(inputId,label,value=NULL,min=NULL,max=NULL, format="yyyy-mm-dd",startview="month",weekstart=0, language="en") value: min/max: format: · The starting date. Either a Date object, or a string in yyyy-mm-dd format.- · The minimum/maximum allowed date. Either a Date object, or a string in yyyy-mm-dd format. - · The format of the date to display in the browser. Defaults: "yyyy-mm-dd".- 64/110
  • 65. Adding widgets Example : dateInput dateInput(inputId,label,value=NULL,min=NULL,max=NULL, format="yyyy-mm-dd",startview="month",weekstart=0, language="en") startview: weekstart: language: · The date range shown when the input object is first clicked. "month" , "year", or "decade". - · Which day is the start of the week.- · The language used for month and day names.- 65/110
  • 66. Date input Adding widgets Example : dataInput dateInput("date", label=h3("Dateinput"), value="2014-01-01") 66/110
  • 67. Adding widgets Example : dateRangeInput dateRangeInput(inputId,label,start=NULL,end=NULL,separator="to",...) start: end: separator: args are same as dateInput · The initial start date. Either a Date object, or a string in yyyy-mm-dd format.- · The initial end date. Either a Date object, or a string in yyyy-mm-dd format.- · String to display between the start and end input boxes.- · 67/110
  • 68. Date range to Adding widgets Example : dateRangeInput dateRangeInput("dates",label=h3("Daterange")) 68/110
  • 69. Adding widgets Example : leInput fileInput(inputId,label,multiple=FALSE,accept=NULL) multiple: accept: · Whether the user should be allowed to select and upload multiple files at once.- · A character vector of MIME types; gives the browser a hint of what kind of files the server is expecting. - 69/110
  • 70. File input No file chosenChoose File Adding widgets Example : leInput fileInput("file",label=h3("Fileinput")) 70/110
  • 71. Adding widgets Example : helpText helpText(...) · One or more help text strings (or other inline HTML elements)- 71/110
  • 72. Help text Note: help text isn't a true widget, but it provides an easy way to add text to accompany other widgets. Adding widgets Example : helpText sidebarPanel( h3("Helptext"), helpText("Note:helptextisn'tatruewidget,", "butitprovidesaneasywaytoaddtextto", "accompanyotherwidgets.")) 72/110
  • 73. Adding widgets Example : numericInput numericInput(inputId,label,value,min=NA,max=NA,step=NA) value: min: max: step: · Initial value- · Minimum allowed value- · Maximum allowed value- · Interval to use when stepping between min and max- 73/110
  • 74. Numeric input 1 Adding widgets Example : numericInput numericInput("num", label=h3("Numericinput"), value=1) 74/110
  • 75. Adding widgets Example : radioButtons radioButtons(inputId,label,choices,selected=NULL) choices: selected: · List of values to select from (if elements of the list are named then that name rather than the value is displayed to the user) - · The initially selected value (if not specified then defaults to the first value)- 75/110
  • 76. Radio buttons Choice 1 Choice 2 Choice 3 Adding widgets Example : radioButtons radioButtons("radio",label=h3("Radiobuttons"), choices=list("Choice1"=1,"Choice2"=2, "Choice3"=3),selected=1) 76/110
  • 77. Adding widgets Example : selectInput selectInput(inputId,label,choices,selected=NULL,multiple=FALSE, selectize=TRUE,...) choices: selected: multiple: selectize: · List of values to select from.- · The initially selected value (or multiple values if multiple = TRUE).- · Is selection of multiple items allowed?- · Whether to use selectize.js or not- 77/110
  • 78. Select box Choice 1 Adding widgets Example : selectInput selectInput("select",label=h3("Selectbox"), choices=list("Choice1"=1,"Choice2"=2, "Choice3"=3),selected=1) 78/110
  • 79. Adding widgets Example : sliderInput sliderInput(inputId,label,min,max,value,step=NULL,round=FALSE,...) min/max: value: step: round: · The minimum/maximum value (inclusive) that can be selected.- · The initial value of the slider.- · Specifies the interval between each selectable value on the slider (NULL means no restriction). - · TRUE to round all values to the nearest integer; FALSE if no rounding is desired; or an integer to round to that number of digits . - 79/110
  • 80. Sliderbar Adding widgets Example : sliderInput sidebarPanel( sliderInput("obs","",0,1000,0) ) 80/110
  • 81. Adding widgets Example : submitButton submitButton(text="ApplyChanges",icon=NULL,...) text: icon: · Button caption- · Optional icon to appear on the button- 81/110
  • 82. SubmitButton Submit Adding widgets Example : submitButton submitButton("Submit") 82/110
  • 83. Adding widgets Example : textInput textInput(inputId,label,value="",...) inputId: label: value: · Input variable to assign the control's value to- · Display label for the control- · Initial value- 83/110
  • 84. Text input Enter text... Adding widgets Example : textInput textInput("text",label=h3("Textinput"), value="Entertext...") 84/110
  • 85. Part 4 : Build reactive output 85/110
  • 86. Preparation Create a folder in your working directory named new_app. Save the ui.Rand server.Rfiles that you make in this section in new_app. · · 86/110
  • 87. Two steps You can create reactive output with a two step process. 1. Add an R object to your user-interface with ui.R. 2. Tell Shiny how to build the object in server.R. The object will be reactive if the code that builds it calls a widget value. 87/110
  • 88. Create UI There are several output functions for creating di erent type of outputs. OUTPUT FUNCTION CREATES htmlOutput raw HTML imageOutput image plotOutput plot tableOutput table textOutput text uiOutput raw HTML verbatimTextOutput text Place the output function inside sidebarPanelor mainPanelin the ui.Rscript.· 88/110
  • 89. Add R objects to ui.R Example for ui.R Use helpText, selectInput, sideInputto input values· shinyUI(fluidPage( titlePanel("RATEME!"), sidebarLayout( sidebarPanel( helpText("Whatdoyouthinkaboutthisapp?"), selectInput("var", label="Chooseonetodisplay", choices=c("awesome","dramastic", "admirable","wonderful"), selected="awesome"), sliderInput("range", label="Persents:", min=90,max=100,value=100) ), 89/110
  • 90. Add R objects to ui.R Example for ui.R mainPanel( textOutput("text1") ) ) )) Use textOutputin mailPanel to show where to place the output. Each of the *Outputfunctions require a single argument: a character string that Shiny will use as the name of your reactive element. Your users will not see this name, but you will use it later. · · · 90/110
  • 91. Show the UI What do you think about this app? Choose one to display Persents: RATE ME! 90 100 awesome shinyapps.io Powered by   91/110
  • 92. Build the object in server.R Placing a function *Outputin ui.Rtells Shiny where to display your object. Provide R code to build the object in server.R. Place the R code in the unnamed functionthat appears inside shinyServerin your server.Rscript. · · · 92/110
  • 93. Build the object in server.R Code in the unnamed function that appears inside shinyServer· #server.R shinyServer(function(input,output){ output$text1<-renderText({ "Youhaveselectedthis" }) } ) 93/110
  • 94. Build the object in server.R Make sure the element name match the name of the reactive element that you created in ui.R. e.g. output$text1matches textOutput("text1")in ui.Rscript. · #server.R shinyServer(function(input,output){ output$text1<-renderText({ "Youhaveselectedthis" }) } ) 94/110
  • 95. render*function RENDER FUNCTION CREATES renderImage images (saved as a link to a source file) renderPlot plots renderPrint any printed output renderTable data frame, matrix, other table like structures renderText character strings renderUI a Shiny tag object or HTML Each entry to output should contain the output of one of Shiny’s render*functions.· Each render*function takes a single argument: an R expression surrounded by braces, {}. · Instructions that you give Shiny to store.- 95/110
  • 96. Make your text reactive Use Inputand Outputin ui.R Make your text reactive by asking Shiny to call a widget value.· Outputstores instructions for building the R objects in your app. Inputstores the current values of all of the widgets in your app. · · 96/110
  • 97. Make your text reactive Example : build a reactive text Assumed our app has two widgets: varand range. #server.R shinyServer(function(input,output){ output$text1<-renderText({ paste("Thisappis",input$range,"%",input$var,"!!!") }) } ) 97/110
  • 98. Show it Use runApp()to show your app What do you think about this app? Choose one to display Persents: RATE ME! 90 100 awesome shinyapps.io Powered by   98/110
  • 99. Part 5 : Use datatable in Shiny Apps 99/110
  • 100. Use datatable in Shiny Apps renderDataTable() The DataTables application demonstrates HTML tables using the jQuery library DataTables. The basic usage: To create an output element in the UI using · · · dataTableOutput(id='foo')` Render a table on the server side using· output$foo<-renderDataTable({data}). 100/110
  • 101. A simple example for renderDataTable The script is as follows: (It's so simple that you don't need to create ui.R,server.R) · runApp(list( ui=basicPage( h2('Themtcarsdata'), dataTableOutput('mytable') ), server=function(input,output){ output$mytable=renderDataTable({ mtcars }) } )) 101/110
  • 102. A simple example for renderDataTable Show it 102/110
  • 103. A complete example for renderDataTable Script of ui.R: A shiny including three datasets: mtcars,iris,diamonds. #ui.R library(shiny) library(ggplot2) #forthediamondsdataset shinyUI(pageWithSidebar( headerPanel('ExamplesofDataTables'), sidebarPanel( checkboxGroupInput('show_vars','Columnsindiamondstoshow:',names(diamonds), selected=names(diamonds)), 103/110
  • 104. A complete example for renderDataTable Script of ui.R helpText('Forthediamondsdata,wecanselectvariablestoshowinthetable; forthemtcarsexample,weusebSortClasses=TRUEsothatsorted columnsarecoloredsincetheyhavespecialCSSclassesattached; fortheirisdata,wecustomizethelengthmenusowecandisplay5 rowsperpage.') ), mainPanel( tabsetPanel( tabPanel('diamonds', dataTableOutput("mytable1")), tabPanel('mtcars', dataTableOutput("mytable2")), tabPanel('iris', dataTableOutput("mytable3")) ) ) )) 104/110
  • 106. A complete example for renderDataTable
  • 107. 108/110 A complete example for renderDataTable
  • 108. 109/110 Summary In this section, you created your first reactive Shiny app. Including:· use an *Outputfunction in the ui.Rscript to place reactive objects in your Shiny app. use a render*function in the server.R script to tell Shiny how to build your objects. surround R expressions by braces, {}, in each render*function. save your render*expressions in the output list, with one entry for each reactive object in your app. create reactivity by including an inputvalue in a render*expression. - - - - -