Below uses dataset mtcars
as the dataset.
An R shiny app is constructed by 2 major parts, UI and SERVER: shinyApp(ui = UI, server = SERVER)
1. UI
UI is how your dashboard appears to the user. It can include the following 3 options: UI = dashboardPage(header = Header, sidebar = Sidebar, body = Body)
-
header:
Header = dashboardHeader(title = 'My Title', titleWidth = 10)
Title of the dashboard page (topleft).
Can also include a dropdown menu on the topright. See help file for function
dashboardHeader()
-
sidebar:
Sidebar <- dashboardSidebar(sidebarMenu( menuItem("Name1", tabName = "Name1content"), menuItem("Name2", tabName = "Name2content") ))
Creates a sidebar dashboard menu. Different selections (
Name1
orName2
) will show on the menu, leading to different main panels.tabName = "Name1content"
links to the body ofName1
’s page in the body part of the UI. -
Body
The main body of the panel. Can include a lot of options:
-
Selector with a dropdown selection list;
-
Check boxes;
-
Buttons;
-
Tables;
-
Plots;
-
…
For each selection of the sidebar (
Name1
orName2
in this case), need to create a separate body, and usetabName = "Name1content"/"Name2content"
to link them:Name1body = tabItem( tabName = "Name1content", ### what you want to show for Name1 ) Name2body = tabItem( tabName = "Name2content", ### what you want to show for Name2 ) Body = dashboardBody( tabItems( Name1body, Name2body ) )
-
2. SERVER
Server defines how functions are actually achieved. It is a function which contains the following 2 arguments: SERVER = function(input, output)
.
You can define an UI in server by renderUI()
and call it in the UI part to show it.
Some useful functions:
-
observeEvent(abc, def)
Do
def
after observingabc
happens. For instanceabc
can be an action button. -
observe(def) %>% bindEvent(abc)
Same as above.
-
output$result1 = renderUI(...)
Then call
result1
in UI part. Same as defining UI directly, but can do more complicated designs (e.g. one input variable depending on another) -
reactive(...)
Wraps a normal expression to create a reactive expression. Often use it to call functions/variables/expressions. (don’t know where exactly this should be used)
-
req(...)
Ensure that a value is available. For example,
req(input$abc)
checks ifinput$abc
exists. If not the App will show empty result (without returning error or break).