We want to create a data application to be posted on a company's website, where users can play interactively with the app, for example change the bin of histograms, ... then shiny, a framework for creating interactive web applications, is the right tool for this.
Shiny tutorial is a good resource for learning: tutorial
A shiny project must have at least two parts:
Example of ui.R:
In [1]:
## ui.R
library(shiny)
shinyUI(pageWithSidebar(
## Header
headerPanel("Hello Shiny World!"),
sidebarPanel(
h3('This is a sidebar created')
),
mainPanel(
h3('This is the main panel')
)
))
In [2]:
## server.R
library(shiny)
shinyServer(
function(input, output) {
## ##
}
)
To run this application, change the working directory to the app directory and use runApp()
The result will be displayed in the browser as below:
In [ ]:
setwd("R-shiny/app-01")
getwd()
list.files()
runApp()
# or use the directory address:
runApp("/home/vahid/GitHub/DataScience/R-shiny/")
Or you can run pre-built examples in the shiny package:
In [ ]:
system.file("examples", package="shiny")
runExample("05_sliders") ## -> interactive slider bars
runExample("06_tabsets") ## -> multiple panels through menu-bar
runExample("10_download") ## -> a wizard to download files
runExample("11_timer") ## -> displays running date and time
Out[ ]:
sidebarLayout to add a sidebar, that needs two arguments
HTML tags can be used directly in ui.R, firexampl p() for < p >, h1() for header < h1 >, img() for < img >
numericInput()
checkboxGroupInput()
dateInput()
submitButton()
In [ ]:
## ui.R
## example for user input and output:
library(shiny)
shinyUI(fluidPage(
titlePanel("Input/output functionality in Shiny!"),
sidebarLayout( position="left",
numericInput("id1", "Number of Random Points", 40, min=10, max=100, step=5),
checkboxGroupInput("id2", "Number of Dimensions:", c("v1"="1", "v2"="2", "v3"="3"))
),
mainPanel(
h2('Output: '),
h3('Distance between class means:'),
verbatimTextOutput("oid1")
)
))
In [ ]:
## server.R
## example for user input and output:
library(shiny)
shinyServer(
function(input, output) {
n <- input$id1 ## number of random points
w1 <- rnorm(n, mean=0, sd=1)
w2 <- rnorm(n, mean=1, sd=2)
m1 <- mean(w1)
m2 <- mean(w2)
output$oid1 <- renderPrint({m1 - m2})
}
)
Reactive expressoin are those which only need to be updated when their input is changed. A reactive expression is made by reactive({}) expression:
Example:
my.react.xpr <- reactive({d <- rnorm(input$id1); mean(d)})
In [ ]: