Shiny Package in R Programming

11 Feb, 2022
The package is an appropriate way to organize the work and share it with others. 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. Shiny is an R package that makes it easy to build interactive web apps straight from R. It helps to host standalone apps on a webpage or embed them in R Markdown documents or build dashboards. One can also extend Shiny apps with CSS themes, htmlwidgets, and JavaScript actions.
To use a package in R programming one must have to install the package first. This task can be done using the command install.packages(“packagename”). To install the whole Shiny package type this:
install.packages("shiny")
To install the latest development builds directly from GitHub, run this instead:
if (!require("remotes"))
  install.packages("remotes")
remotes::install_github("rstudio/shiny")
fluidPage(): It creates a page with a fluid layout. A fluid page layout consists of rows which in turn include columns. Rows exist for the purpose of making sure their elements appear on the same line and columns exist for the purpose of defining how much horizontal space within a 12-unit wide grid. Fluid pages scale their components in real-time to fill all available browser width.
   Syntax:
   fluidPage(..., title = NULL, theme = NULL)
Description
Example:
This is a basic shiny app template. 
R
# import shiny packagelibrary(shiny) # define a page with fluid layoutui <- fluidPage(h1("GeeksforGeeks article on shiny package in R"),                p(style = "font-family:Impact", "My first shiny app"))server <- function(input, output) {} shinyApp(ui = ui, server = server)
 Output:
shinyApp(): It creates Shiny app objects from either an explicit UI/server pair or bypassing the path of a directory that contains a Shiny app.
   Syntax:
   shinyApp(ui, server, onStart = NULL, options = list(), uiPattern = “/”, enableBookmarking = NULL)
   shinyAppDir(appDir, options = list())
   shinyAppFile(appFile, options = list())</p  
Description
It has three parameters: input, output, and session.
It is called once for each session to ensure that each app is independent.
A regular expression that will be applied to each 
GET request to determine whether the ui should be used to handle the request.
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- 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))  })} # create shiny app object# using shinyAppshinyApp(ui = ui, server = server)
 Output:
reactive(): It creates a reactive expression. A reactive expression is an expression whose result will change over time.reactive() wraps a normal expression to create a reactive expression.
   Syntax: reactive(x, env = parent.frame(), quoted = FALSE, label = NULL)
Description
Is the expression quoted? By default, this is FALSE. 
This is useful when you want to use an expression that is stored in a variable
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- fluidPage(  textInput(inputId = "num", label = "Choose a number",            value = "", width = 100, placeholder = NULL),  plotOutput("hist"),  verbatimTextOutput("stats"))server <- function(input, output){  # use reactive to create  # a reactive expression  data <- reactive({rnorm(input$num)})     output$hist <- renderPlot({hist(data())})  output$stats <- renderPrint({summary(data())})} # create shiny app object# using shinyAppshinyApp(ui = ui, server = server)
Output:
Now, change the input value from 50 to 100 to see what happens.
The output values(histogram and summary) also change with the alternation in the input values, i.e the app has reactivity.
observeEvent(): It triggers code to run on servers. Respond to “event-like” reactive inputs, values, and expressions.
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)
Description
A expression that represents the event.It can be
 a simple or a complex reactive expression.
The parent environment for eventExpr. 
By default, this is the calling environment.
Returns whether the eventExpr expression is quoted or not.
 By default, this is FALSE.
Returns whether the handlerExpr expression is quoted or not.
 By default, this is FALSE.
An integer or numeric that controls the priority 
with which this observer should be executed.Positive,Negative and Zero values are allowed.
If TRUE (the default), the observer will be automatically 
destroyed when its domain (if any) ends.
If TRUE, then, when this observeEvent is first created/initialized,
ignore the handlerExpr (the second argument), whether
 it is otherwise supposed to run or not. The default is FALSE.
Whether this observeEvent should be immediately destroyed after
 the first time that the code in handlerExpr is run.
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui = fluidPage(  textInput(inputId = "num",            label = "Enter a numeric value", value = "10"),            actionButton("button", "Calculate"),  column(8, tableOutput("table"))) server = function(input, output){  # Take an action every time button is pressed  observeEvent(input$button, {    cat("Showing", input$num, "rows\n")  })     # Take a reactive dependency  # on input$num, but not on any  # of the stuff inside the function  df <- eventReactive(input$button, {    head(cars, input$num)  })  output$table <- renderTable({    df()  })} # create shiny app object# using shinyAppshinyApp(ui, server)
Output:
eventReactive(): A reactive expression that only responds to specific values. Respond to “event-like” reactive inputs, values, and 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)
Description
If TRUE, then, when this observeEvent is first created/initialized,
 ignore the handlerExpr (the second argument), whether
 it is otherwise supposed to run or not. The default is FALSE.
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- fluidPage(  sliderInput(inputId = "num",              label = "Choose a number",              value = 25, min = 1, max = 100),  actionButton(inputId = "go",               label = "Update"),  plotOutput("hist")) server <- function(input, output){  data <- eventReactive(input$go, {    rnorm(input$num)  })     output$hist <- renderPlot({    hist(data())  })} # create shiny app object# using shinyAppshinyApp(ui = ui, server = server)
 Output:
Here, the output does not change with the input values until and unless the update button is triggered
actionButton(): It creates an action button or a link. Their initial value is zero, and increments by one each time it is pressed.
   Syntax:
   actionButton(inputId, label, icon = NULL, width = NULL, ...)
   actionLink(inputId, label, icon = NULL, ...)
Description
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- fluidPage(  sliderInput("obs", "Number of observations", 0, 1000, 500),  actionButton("goButton", "Go!", class = "btn-success"),  plotOutput("distPlot")) server <- function(input, output){  output$distPlot <- renderPlot({    input$goButton    dist <- isolate(rnorm(input$obs))    hist(dist)  })} # create shiny app object# using shinyAppshinyApp(ui, server)
 Output:
The output gets updated as soon as the actionButton(Go!) is clicked.
checkboxGroupInput(): It creates a group of checkboxes that can be used to toggle multiple choices independently. The server will receive the input as a character vector of the selected values.
Syntax:
checkboxGroupInput(inputId, label, choices = NULL, selected = NULL, inline = FALSE, width = NULL, choiceNames = NULL, choiceValues = NULL)
Parameter
Description
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.
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- fluidPage(  checkboxGroupInput("icons", "Choose icons:",                     choiceNames =                       list(icon("dog"), icon("cat"),                            icon("fish"), icon("bug")),                     choiceValues =                       list("dog", "cat", "fish", "bug")),                     textOutput("txt")) server <- function(input, output, session){  output$txt <- renderText({    icons <- paste(input$icons, collapse = ", ")    paste("You chose", icons)  })} # create shiny app object# using shinyAppshinyApp(ui = ui, server = server)
 Output:
textInput(): It creates a text input label.
   Syntax:
   textInput(inputId, label, value = “”, width = NULL, placeholder = NULL)
Description
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- fluidPage(  textInput("txt", "Enter your text here", "Empty"),  verbatimTextOutput("value")) server <- function(input, output){  output$value <- renderText({ input$text })} # create shiny app object# using shinyAppshinyApp(ui, server)
 Output:
textOutput(): It creates a text output element. Render a reactive output variable as text within an application page.
   Syntax:
   textOutput(outputId, container = if (inline) span else div, inline = FALSE)
Description
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- fluidPage( textInput(inputId = "Name", label = "Enter your name"), textOutput("txt")) server <- function(input, output, session){  output$txt <- renderText({    Name <- paste(input$Name, collapse = ", ")    paste("Welcome! to geeksforgeeks ", Name)  })} # create shiny app object# using shinyAppshinyApp(ui = ui, server = server)
 Output:
wellPanel(): Creates a panel with a slightly inset border and gray background.
   Syntax: wellPanel(...)
Description
Example:
R
# import shiny packagelibrary(shiny) # define fluid page layoutui <- fluidPage(    sliderInput(inputId = "num",                label = "Choose a number",                value = 25, min = 1, max = 100),    # define plot inside # a wellPanel wellPanel(plotOutput("hist"))) server <- function(input, output){  output$hist <- renderPlot({    hist(rnorm(input$num), main = input$title)  })} # create shiny app object# using shinyAppshinyApp(ui = ui, server = server)
 Output: 
Observe that the histogram lies inside a gray-colored box(wellPanel).
kumar_satyam
sumitgumber28
R-Packages
Machine Learning
R Language
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.