What are the best practices to organize larger Shiny applications?
I think best R practices are also applicable to Shiny.
Best R practices are discussed here: How to organize large R programs
Link to Google's R Style Guide: Style Guide
But what are the unique tips and tricks in Shiny context which I can adopt to make my Shiny code look better (and more readable)? I am thinking of things like:
- Exploiting object oriented programming in Shiny
- In
server.R
which parts should be sourced? - File hierarchy of project containing markdown documents, pictures, xml and source files
For example if I am using navbarPage
and tabsetPanel
in every tabPanel
my code is starting to look quite messy after addition of several UI elements.
Example code:
server <- function(input, output) {
#Here functions and outputs..
}
ui <- shinyUI(navbarPage("My Application",
tabPanel("Component 1",
sidebarLayout(
sidebarPanel(
# UI elements..
),
mainPanel(
tabsetPanel(
tabPanel("Plot", plotOutput("plot")
# More UI elements..
),
tabPanel("Summary", verbatimTextOutput("summary")
# And some more...
),
tabPanel("Table", tableOutput("table")
# And...
)
)
)
)
),
tabPanel("Component 2"),
tabPanel("Component 3")
))
shinyApp(ui = ui, server = server)
For organizing ui.R
code I found quite nice solution from GitHub: radiant code
Solution is to use renderUI
to render every tabPanel
and in server.R
tabs are sourced to different files.
server <- function(input, output) {
# This part can be in different source file for example component1.R
###################################
output$component1 <- renderUI({
sidebarLayout(
sidebarPanel(
),
mainPanel(
tabsetPanel(
tabPanel("Plot", plotOutput("plot")),
tabPanel("Summary", verbatimTextOutput("summary")),
tabPanel("Table", tableOutput("table"))
)
)
)
})
#####################################
}
ui <- shinyUI(navbarPage("My Application",
tabPanel("Component 1", uiOutput("component1")),
tabPanel("Component 2"),
tabPanel("Component 3")
))
shinyApp(ui = ui, server = server)
See Question&Answers more detail:os