This is a event given by Vivian Zhang at NYC Open Data Meetup
Training brand under SupStat Inc.
We challenge traditional data analysis thinking, train and inspire the next generation of data scientists and data visualization professionals. We don’t just teach our courses here at Data Academy, we live them in our consulting business. Our courses are designed and taught in house and under the mentorship from industry leaders and experts.
We offer 12 week full-time bootcamp, corporate training, and weekend classes on the topics of R/Python beginner(data analytics focus), R/Python Intermediate (machine learning focus), Hadoop Beginner, Intermediate(Real world cases focus), etc. It attracts a lot of companies to hire our graduates directly from us: http://nycdatascience.com/bootcamp/
5 Weekend classes are consisted of 20 to 35 hours of classroom guidance with a three week-long showcase project and presentation night. Email info@nycdatascience.com to get enrolled or engaged as students or hiring partners. http://nycdatascience.com/courses
We have provided technical training for corporations and individuals including Google, Dow Jones, Bloomberg, Thomson Reuters, AIG, Citibank, PWC, Roche, Locus Analytics, MSKCC, Rosetta, Gilt Group, Deutsche Bank, Xaxis(WPP), AppNexus, Viacom, NBA, HBO,Federal Reserve Bank, BlackRock, Real Capital Analytics, NBC universal, FINRA, etc.
All the corporate trainings are highly customized based on clients' need. Email info@nycdatascience.com for case study.
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.
-
-
-
-
-