Shiny Package in R Programming

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)
ParameterDescription
Elements to include within the page.
titleThe browser window title.
themeAn 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())
ParameterDescription
uiThe UI definition of the app.
serverServer logic containing inputoutputsession.
onStartFunction to call before the app runs.
optionsOptions passed to runApp.
uiPatternRegular expression to match GET requests.
enableBookmarkingCan 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)
ParameterDescription
xAn expression.
envParent environment for the expression.
quotedWhether the expression is quoted (default: FALSE).
labelA 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)
ParameterDescription
eventExprReactive expression triggering the event.
handlerExprCode to execute when eventExpr is invalidated.
ignoreNULLIgnore the action when input is NULL (default: TRUE).
onceWhether 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

ParameterDescription
eventExprThe expression representing the event, which can be a simple or complex reactive expression.
valueExprProduces the return value of eventReactive. Executes within an isolate() scope.
event.envParent environment for eventExpr. Default is the calling environment.
event.quotedIndicates if eventExpr is quoted. Default is FALSE.
value.envParent environment for valueExpr. Default is the calling environment.
value.quotedIndicates if valueExpr is quoted. Default is FALSE.
ignoreNULLDetermines if action should trigger when the input is NULL.
ignoreInitIf 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

ParameterDescription
inputIdID for accessing the button value.
labelText displayed on the button.
iconIcon to display with the button (optional).
widthWidth 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

ParameterDescription
inputIdID for accessing the selected checkbox values.
labelLabel displayed above the checkboxes.
choicesList of values for the checkboxes. If named, the name is displayed instead of the value.
selectedInitial selected value(s).
inlineIf TRUE, renders the checkboxes horizontally.
widthWidth of the input element.
choiceNamesNames displayed for the choices.
choiceValuesValues 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:

ParameterDescription
inputIdThe ID of the input element, used to retrieve the value in the server function.
labelThe text label displayed for the input box.
valueThe initial value of the input box (optional).
widthSpecifies the width of the input box (e.g., ‘300px’, ‘50%’).
placeholderProvides 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:

ParameterDescription
outputIdThe ID used to access the output text in the server.
containerA function (e.g., divspan) that wraps the output HTML element.
inlineBoolean 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:

ParameterDescription
...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.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *