Example: A Shiny Application
This example demonstrates how to create and run a Shiny application and view the associated UI while in an active session.
Create a new, blank project and run an R console. Create the files,
ui.R
and server.R
, in the project,
and copy the contents of the following example files provided by Shiny
by RStudio:
R
# ui.R
library(shiny)
# Define UI for application that draws a histogram
shinyUI(fluidPage(
# Application title
titlePanel("Hello Shiny!"),
# Sidebar with a slider input for the number of bins
sidebarLayout(
sidebarPanel(
sliderInput("bins",
"Number of bins:",
min = 1,
max = 50,
value = 30)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
))
R
# server.R
library(shiny)
# Define server logic required to draw a histogram
shinyServer(function(input, output) {
# Expression that generates a histogram. The expression is
# wrapped in a call to renderPlot to indicate that:
#
# 1) It is "reactive" and therefore should re-execute automatically
# when inputs change
# 2) Its output type is a plot
output$distPlot <- renderPlot({
x <- faithful[, 2] # Old Faithful Geyser data
bins <- seq(min(x), max(x), length.out = input$bins + 1)
# draw the histogram with the specified number of bins
hist(x, breaks = bins, col = 'darkgray', border = 'white')
})
})
Run the following code in the interactive workbench prompt to install
the Shiny package, load the library into the engine, and run the Shiny
application. R
install.packages('shiny')
library('shiny')
runApp(port=as.numeric(Sys.getenv("CDSW_PUBLIC_PORT")), host="127.0.0.1", launch.browser="FALSE")
Finally, to access the web application, either:
- Click the grid icon in the upper right hand corner of the Cloudera Data Science Workbench web application, and select the Shiny UI, Hello Shiny!, from the dropdown.
- Access the web application directly by visiting the URL: https://public-[session-id].[CML host]/