Shiny Package in detail
Packages in the R programming language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the Shiny package, which makes it easy to build interactive web applications directly from R.
Installing the Shiny Package in R
To use a package in R, it must be installed first. This can be done using the install.packages("packagename") command. To install the Shiny package, use the following command:
install.packages("shiny")
To install the latest development builds directly from GitHub, use this:
if (!require("remotes"))
install.packages("remotes")
remotes::install_github("rstudio/shiny")
Important Functions in the Shiny Package
1. fluidPage():The fluidPage() function creates a page with a fluid layout. A fluid layout consists of rows that include columns. Rows ensure their elements appear on the same line, while columns define the horizontal space within a 12-unit-wide grid. Fluid pages scale their components dynamically to fit the available browser width.
Syntax:
fluidPage(…, title = NULL, theme = NULL)
| Parameter | Description |
|---|---|
… | Elements to include within the page. |
title | The browser window title. |
theme | An alternative Bootstrap stylesheet. |
Example:
# Import shiny package
library(shiny)
# Define a page with a fluid layout
ui <- fluidPage(
h1("Interactive App with Shiny"),
p(style = "font-family:Arial", "This is a simple Shiny app")
)
server <- function(input, output) {}
shinyApp(ui = ui, server = server)
Output:
2. shinyApp(): The shinyApp() function creates Shiny app objects by combining UI and server components. It can also take the path of a directory containing a Shiny app.
Syntax:
shinyApp(ui, server, onStart = NULL, options = list(), uiPattern = "/", enableBookmarking = NULL)
shinyAppDir(appDir, options = list())
shinyAppFile(appFile, options = list())
| Parameter | Description |
ui | The UI definition of the app. |
server | Server logic containing input, output, session. |
onStart | Function to call before the app runs. |
options | Options passed to runApp. |
uiPattern | Regular expression to match GET requests. |
enableBookmarking | Can be “url”, “server”, or “disable”. Default is NULL. |
Example:
# Import shiny package
library(shiny)
# Define fluid page layout
ui <- fluidPage(
sliderInput(
inputId = "num",
label = "Choose a number",
value = 10,
min = 1,
max = 1000
),
plotOutput("hist")
)
server <- function(input, output) {
output$hist <- renderPlot({
hist(rnorm(input$num))
})
}
shinyApp(ui = ui, server = server)
Output:
3. reactive(): The reactive() function creates a reactive expression, which updates whenever its dependencies change.
Syntax:
reactive(x, env = parent.frame(), quoted = FALSE, label = NULL)
| Parameter | Description |
x | An expression. |
env | Parent environment for the expression. |
quoted | Whether the expression is quoted (default: FALSE). |
label | A label for the reactive expression. |
Example:
# Import shiny package
library(shiny)
# Define fluid page layout
ui <- fluidPage(
numericInput("num", "Enter a number", value = 10),
plotOutput("hist"),
verbatimTextOutput("stats")
)
server <- function(input, output) {
data <- reactive({
rnorm(input$num)
})
output$hist <- renderPlot({
hist(data())
})
output$stats <- renderPrint({
summary(data())
})
}
shinyApp(ui = ui, server = server)
Output:
4. observeEvent(): The observeEvent() function responds to event-like reactive inputs and triggers specific code on the server side.
Syntax:
observeEvent(eventExpr, handlerExpr,
event.env = parent.frame(), event.quoted = FALSE,
handler.env = parent.frame(), handler.quoted = FALSE,
label = NULL, suspended = FALSE, priority = 0,
domain = getDefaultReactiveDomain(), autoDestroy = TRUE,
ignoreNULL = TRUE, ignoreInit = FALSE, once = FALSE)
| Parameter | Description |
eventExpr | Reactive expression triggering the event. |
handlerExpr | Code to execute when eventExpr is invalidated. |
ignoreNULL | Ignore the action when input is NULL (default: TRUE). |
once | Whether the event is triggered only once. |
Example:
# Import shiny package
library(shiny)
# Define fluid page layout
ui <- fluidPage(
numericInput("num", "Enter a number", value = 10),
actionButton("calculate", "Show Data"),
tableOutput("table")
)
server <- function(input, output) {
observeEvent(input$calculate, {
num <- as.numeric(input$num)
if (is.na(num)) {
cat("Invalid numeric value entered.\n")
return(NULL)
}
cat("Displaying data for", num, "rows.\n")
})
df <- eventReactive(input$calculate, {
num <- as.numeric(input$num)
if (is.na(num)) {
return(NULL)
}
head(mtcars, num)
})
output$table <- renderTable({
df()
})
}
shinyApp(ui = ui, server = server)
Output:
Random Rows:
Name Age Height
1 Sanjay 30 5.9
2 Meera 24 NA
Random Fraction:
Name Age Height
1 Anita 28 5.4
2 Rahul 25 NA
5. eventReactive() in Shiny:eventReactive() is used to create a reactive expression that triggers only when specific events occur. It listens to “event-like” reactive inputs, values, or expressions.
Syntax
eventReactive(eventExpr,
valueExpr,
event.env = parent.frame(),
event.quoted = FALSE,
value.env = parent.frame(),
value.quoted = FALSE,
label = NULL,
domain = getDefaultReactiveDomain(),
ignoreNULL = TRUE,
ignoreInit = FALSE)
Parameters
| Parameter | Description |
|---|---|
eventExpr | The expression representing the event, which can be a simple or complex reactive expression. |
valueExpr | Produces the return value of eventReactive. Executes within an isolate() scope. |
event.env | Parent environment for eventExpr. Default is the calling environment. |
event.quoted | Indicates if eventExpr is quoted. Default is FALSE. |
value.env | Parent environment for valueExpr. Default is the calling environment. |
value.quoted | Indicates if valueExpr is quoted. Default is FALSE. |
ignoreNULL | Determines if action should trigger when the input is NULL. |
ignoreInit | If TRUE, ignores the handler expression when first initialized. Default is FALSE. |
Example: Using eventReactive
library(shiny)
ui <- fluidPage(
sliderInput(inputId = "num",
label = "Choose a number",
value = 25, min = 1, max = 100),
actionButton(inputId = "update",
label = "Update"),
plotOutput("histogram")
)
server <- function(input, output) {
data <- eventReactive(input$update, {
rnorm(input$num)
})
output$histogram <- renderPlot({
hist(data())
})
}
shinyApp(ui = ui, server = server)
Output:
6. actionButton() in Shiny: actionButton() creates a button that triggers an action when clicked.
Syntax
actionButton(inputId, label, icon = NULL, width = NULL, ...)
Parameters
| Parameter | Description |
|---|---|
inputId | ID for accessing the button value. |
label | Text displayed on the button. |
icon | Icon to display with the button (optional). |
width | Width of the button (e.g., ‘200px’, ‘100%’). |
... | Additional attributes for the button. |
Example: Using actionButton
library(shiny)
ui <- fluidPage(
sliderInput("obs", "Number of Observations", min = 1, max = 1000, value = 500),
actionButton("goButton", "Generate Plot"),
plotOutput("plot")
)
server <- function(input, output) {
output$plot <- renderPlot({
input$goButton
isolate({
dist <- rnorm(input$obs)
hist(dist)
})
})
}
shinyApp(ui, server)
Output:
7. checkboxGroupInput() in Shiny:checkboxGroupInput() creates a group of checkboxes for selecting multiple options.
Syntax
checkboxGroupInput(inputId, label, choices = NULL, selected = NULL, inline = FALSE, width = NULL, choiceNames = NULL, choiceValues = NULL)
Parameters
| Parameter | Description |
|---|---|
inputId | ID for accessing the selected checkbox values. |
label | Label displayed above the checkboxes. |
choices | List of values for the checkboxes. If named, the name is displayed instead of the value. |
selected | Initial selected value(s). |
inline | If TRUE, renders the checkboxes horizontally. |
width | Width of the input element. |
choiceNames | Names displayed for the choices. |
choiceValues | Values corresponding to the choices. |
Example: Using checkboxGroupInput
library(shiny)
ui <- fluidPage(
checkboxGroupInput("choices", "Select Options:",
choiceNames = list("Apple", "Banana", "Cherry", "Date"),
choiceValues = list("apple", "banana", "cherry", "date")),
textOutput("selection")
)
server <- function(input, output) {
output$selection <- renderText({
paste("You selected:", paste(input$choices, collapse = ", "))
})
}
shinyApp(ui = ui, server = server)
8. textInput(): This function creates a text input box for users to enter text.
Syntax:
textInput(inputId, label, value = "", width = NULL, placeholder = NULL)
Parameters:
| Parameter | Description |
|---|---|
inputId | The ID of the input element, used to retrieve the value in the server function. |
label | The text label displayed for the input box. |
value | The initial value of the input box (optional). |
width | Specifies the width of the input box (e.g., ‘300px’, ‘50%’). |
placeholder | Provides a hint about the expected input in the box. |
Example: Simple Text Input and Display
# Load Shiny library
library(shiny)
# UI layout
ui <- fluidPage(
textInput("userText", "Enter text here:", "Type something"),
verbatimTextOutput("displayText")
)
# Server logic
server <- function(input, output) {
output$displayText <- renderText({ input$userText })
}
# Create Shiny app
shinyApp(ui = ui, server = server)
Output:
A text input box appears, where users can type text. The entered text is displayed below the input box.
9. textOutput():
This function creates an output text element to display reactive text in your Shiny app.
Syntax:
textOutput(outputId, container = if (inline) span else div, inline = FALSE)
Parameters:
| Parameter | Description |
|---|---|
outputId | The ID used to access the output text in the server. |
container | A function (e.g., div, span) that wraps the output HTML element. |
inline | Boolean value indicating if the output should be displayed inline or block. |
Example: Welcome Message
# Load Shiny library
library(shiny)
# UI layout
ui <- fluidPage(
textInput("userName", "Enter your name:"),
textOutput("welcomeText")
)
# Server logic
server <- function(input, output, session) {
output$welcomeText <- renderText({
paste("Hello,", input$userName, "! Welcome to the Shiny app.")
})
}
# Create Shiny app
shinyApp(ui = ui, server = server)
10. wellPanel():
This function creates a bordered box with a gray background to highlight specific elements in your app.
Syntax:
wellPanel(...)
Output:
A text input box appears, where users can type text. The entered text is displayed below the input box.
Parameters:
| Parameter | Description |
|---|---|
... | UI elements to be placed inside the panel. |
Example: Histogram Inside a Panel
# Load Shiny library
library(shiny)
# UI layout
ui <- fluidPage(
sliderInput("numValues", "Choose a number:", min = 10, max = 100, value = 50),
wellPanel(
plotOutput("histPlot")
)
)
# Server logic
server <- function(input, output) {
output$histPlot <- renderPlot({
hist(rnorm(input$numValues), col = "lightblue", main = "Sample Histogram")
})
}
# Create Shiny app
shinyApp(ui = ui, server = server)
Output:
A histogram is displayed inside a gray-bordered well panel. The number of data points is controlled by a slider.
Enhanced Example: Interactive Scatter Plot
# Load Shiny library
library(shiny)
# UI layout
ui <- fluidPage(
titlePanel("Interactive Scatter Plot"),
sidebarLayout(
sidebarPanel(
numericInput("numPoints", "Number of Points:", value = 50, min = 10, max = 100),
br(),
actionButton("updateBtn", "Generate Plot")
),
mainPanel(
plotOutput("scatterPlot", height = "400px")
)
)
)
# Server logic
server <- function(input, output) {
# Reactive function to generate data
scatterData <- reactive({
data.frame(
x = rnorm(input$numPoints),
y = rnorm(input$numPoints)
)
})
# Render scatter plot
observeEvent(input$updateBtn, {
output$scatterPlot <- renderPlot({
plot(
scatterData()$x, scatterData()$y,
main = "Scatter Plot",
xlab = "X-axis", ylab = "Y-axis",
col = "blue", pch = 19, xlim = c(-3, 3), ylim = c(-3, 3)
)
})
})
}
# Create Shiny app
shinyApp(ui = ui, server = server)
Output:
An interactive scatter plot is displayed. Users can control the number of points with a numeric input and update the plot using a button.
Leave a Reply