Introduction
This article outlines how I structure my R Shiny codebase. Whenever I start a new Shiny application, I use the following structure:
|
|
Separation of UI Logic and Server Logic
In Mastering Shiny by Hadley Wickham, the ui and server logic are combined in app.R
. However, I prefer to separate them into ui.R
and server.R
for better organization.
Template for server.R
|
|
I always set a seed for reproducibility, ensuring consistency in functions that involve pseudo-randomness (e.g., random sampling).
Example of ui.R
|
|
This setup leverages the fresh package for theming alongside bs4Dash.
Global Functions and Variables
The global.R
file is automatically recognized by Shiny. It stores global variables and functions used throughout the application. For specific functions, I place them in the utils/
directory.
Template for global.R
|
|
This ensures all modules and utility functions are automatically loaded.
Example of global.R
|
|
The theme
variable is referenced in ui.R to apply consistent styling.
Utilities (utils/
)
Example: utils/ticker_utils.R
|
|
Modules (modules/
)
Shiny modules allow for better reusability and maintainability.
Example: modules\watchlist_mod.R
|
|
Another example: modules\vix_value_box_mod.R
|
|
Conclusion
This structure keeps my Shiny applications modular, maintainable, and scalable. By separating UI logic, server logic, global functions, utility functions, and modules, I ensure better readability and reusability across projects.