13.2 Structure of a Shiny app

A Shiny app can be built by creating a directory (called, for example, appdir) that contains an R file (called, for example, app.R) with three components:

  • a user interface object (ui) which controls the layout and appearance of the app,

  • a server() function which contains the instructions to build the objects displayed in the user interface, and

  • a call to the shinyApp() function that creates the app from the ui/server pair.

# load the shiny package
library(shiny)

# define user interface object
ui <- fluidPage()

# define server function
server <- function(input, output) { }

# call to shinyApp() which returns a Shiny app object from an
# explicit UI/server pair
shinyApp(ui = ui, server = server)

Note that the directory can also contain other files such as data or R scripts that are needed by the app. Then we can launch the app by typing runApp(“appdir_path”) where appdir_path is the path of the directory that contains the app.R file.

library(shiny)
runApp("appdir_path")
  • If we open the app.R file in RStudio, we can also launch the app by clicking the Run button of RStudio. We can stop the app by clicking escape or the stop button in our R environment.

  • An alternative approach to create a Shiny app is to write two separate files ui.R and server.R containing the user interface object and the server function, respectively. Then the app can be launched by calling runApp(“appdir_path”) where appdir_path is the path of the directory where both the ui.R and server.R files are saved. Creating an app with this alternative approach may be more appropriate for large apps because it permits an easier management of the code.