Shiny Useful Code
Created by Chia, Jonathan, last modified on Apr 09, 2022
Introduction
For making production ready shiny dashboards - table of contents in no particular order
Note: this article assumes reader already has a basic shiny understanding
Table of Contents
Why Use Shiny?
Shiny is a simple extension of R
Shiny provides detailed customization but an easy framework
Setup Dashboard URL
Log into bi-rstudio - you will create your dashboard on this server so people in the company can access through a URL link
Create a ShinyApps folder in your home directory

In your Shiny Apps folder, create a folder for your dashboard - here we named it mydashboard

Now people can access your dashboard through http://bi-rstudio:3838/yourusername/mydashboard/
Finally, in the mydashboard folder, create a R file named "app.R"
The URL link only works if you have a folder named ShinyApps, a dashboard folder, and then an app.R file.
Login/Authentication
For better security, create an authentication page for the dashboard

UI
Server
Tip: For credentials_df, create it using config file
IMPORTANT NOTE:
observe() function will not work because of the authentication page unless you use the below code:
Additionally, sometimes observeEvent() function will trigger at initialization because of the authentication page. Set init = FALSE to avoid this issue:
Display Markdown/HTML Documents
Markdown documents can be very good for explanation pages in dashboards.
markdown/html in shiny: https://shiny.rstudio.com/gallery/including-html-text-and-markdown-files.html
markdown cheat sheet: https://www.markdownguide.org/cheat-sheet/
Email DataTable as CSV/Excel within Company through SMTP
Create an email button:

Clicking the green email button reveals this dropdown:

UI
Server
Download DataTable as CSV/Excel

UI
Server
Create Report Compiler Tab
Users can compile a report in word/html using screenshots through this tab

How to build:
Create screenshot button
Create report compiling tab
Screenshot Button
Adds screenshot button to top right corner of the dashboard

UI
Server
Report Tab
UI
Server
Documents - YOU WILL NEED THESE FILES
report_compiler_md.Rmd
report_compiler_html.Rmd - same as above but with output: html_document
report_compiler_word.Rmd - same as above but with output: word_document
DataTable Formatting Function Examples
DataTable formatting is an absolute pain and takes forever. Below are some functions I use to make life easier:
Number Formatting
Function
Server Example
Server without function
Border Formatting
Function
Conditional Formatting
The below function is more complicated. Ask Jonathan or Tyki for an explanation if it is confusing.
Function
Notes:
Datatable$x$data references the dataframe that was put into the datatable() function
Reference: https://rstudio.github.io/DT/functions.html
Build your own functions using the same strategies from these formulas
Shiny Widgets - Dropdown, Sweet Alerts, PickerInput, SwitchInput, etc.
This package provides improved UI widgets such as pickerInput(), dropdownButton(), and sweet alerts
https://dreamrs.github.io/shinyWidgets/index.html

When to use Column() vs. SplitLayout()
SplitLayout() automatically places UI widgets equally spread apart, so it's easier to use
UI - sliderinput will take up half of the screen and plot output will take up the other half
Column() gives you full control of UI widget location, so it gives more detailed fine-tuning
UI - slider input takes up 1/3 of the screen and plot output takes up 2/3
IMPORTANT NOTE: use column() if selectInput() dropdown doesn't dropdown fully
Using SplitLayout()

Using column()

Adding Tool Tips
Put tool tips over/under widgets

UI
Useful Database Connection Functions
Connection
Close connection at end of app
Write data.frame() to Oracle
Append data to global temporary table in oracle
Lazy Load table from oracle into R - see DBPLYR section for more details
Highchart Visualization Tips
I highly recommend using highcharts for best-in-class tooltips and visualizations
https://jkunst.com/highcharter/
Example:

Non-Standard Evaluation (NSE) of columns
Problem:
Solution:
This solution should work in other scenarios outside of highchart visualizations as well
Tool Tips
Below is an example of a tooltip. The dataframe has three columns: Gemstone, Placed_Orders, and Percent_Placed_Orders
To add a tooltip, all you need is point.Variable_Name
Another example with number formatting and adding a percentage sign to the end of percent_placed_orders:

You can add them to series
Y axis formatting
Here's how you add percentage to the y axis
Regression Line
SUPER USEFUL WEBSITE
https://www.tmbish.me/lab/highcharter-cookbook/
Highchart Thousands Separator (Get rid of the spaces and put commas instead)
Information Button on Header
After clicking the top right information button, display a markdown document in a modal window

UI
Server
TabsetPanels()
Tabset Panels are really help to organize dashboards. For example:

https://shiny.rstudio.com/gallery/tabsets.html
Good Color Schemes
To find good color gradients, see this website:
https://learnui.design/tools/data-color-picker.html
(Can also use this to find colors for conditional formatting)
Icons
For anytime you use icon=icon() in actionButtons, actionLinks, sidebar tabs, etc.

https://fontawesome.com/icons?d=gallery
Progress Loading Bars
Helps executives not get frustrated with wait times when you perform high-intensive computations

https://shiny.rstudio.com/gallery/progress-bar-example.html
Dashboard Logs
Sends log information to table in database. Big thanks to Gable for the code on this:
Server
UI - input$tabs comes from the id in the sidebar
Pool Package and Handling Connections
Best Solution
The pool package is the best way to handle complex dashboards with multiple connections; however, I haven't had any success with pool and odbc package
https://shiny.rstudio.com/articles/overview.html
Current Solution
Initialize one connection at beginning of server and then close it at the end of the session
Show/Hide Tabset Panels
Here is an example for how to show/hide tabset panels using a switch input button:

UI
Here are the tabsetpanels - they will be hidden if the switch input is clicked

Server
Dbplyr
"dbplyr is the database backend for dplyr. It allows you to use remote database tables as if they are in-memory data frames by automatically converting dplyr code into SQL."
Dbplyr is useful when working with tables that are way too big to download into R.
Value Box Headers


Headers can have subtext, icons, and different colors
UI
Server
Force Update/Restart of the Application
Problem: after updating data/code in the dashboard, the application doesn't update if someone has the dashboard open on one of their browser tabs - even if they are logged out/timed out.
Solution:
Create a blank text file named 'restart.txt' in the application directory. This will start a 'new R process to run the "new" (restarted) Shiny Application for this and future users'.
Old sessions will remain unchanged until old user refreshes/relogs in. This shouldn't be a problem though because dashboard can be build to time out (see table of contents) Make a bash file that runs 'touch restart.txt' to restart the app every day at a specific time. The Shiny Server updates based on the modified time of the 'restart.txt' file. Documentation: http://rstudio.github.io/shiny-server/os/0.4.0/#restarting-an-application
Shiny Reports using R Markdown
https://github.com/davidruvolo51/shinyAppTutorials/tree/main/rmarkdown-app
https://shiny.rstudio.com/articles/generating-reports.html
I believe this is the solution to automating executive dashboard reports. If you want to see an example, check out the executive_report folder in the executive dashboard.
To Add
DataTable Row Last Clicked/Row Selected
SQL Queries and preventing SQL Injections
Document generated by Confluence on Apr 09, 2022 16:54
Last updated