2 min read

R shiny #1

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)

  1. 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()

  2. sidebar:

    Sidebar <- dashboardSidebar(sidebarMenu(
      menuItem("Name1", tabName = "Name1content"),
      menuItem("Name2", tabName = "Name2content")
    ))
    

    Creates a sidebar dashboard menu. Different selections (Name1 or Name2) will show on the menu, leading to different main panels. tabName = "Name1content" links to the body of Name1’s page in the body part of the UI.

  3. 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 or Name2 in this case), need to create a separate body, and use tabName = "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:

  1. observeEvent(abc, def)

    Do def after observing abc happens. For instance abc can be an action button.

  2. observe(def) %>% bindEvent(abc)

    Same as above.

  3. 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)

  4. 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)

  5. req(...)

    Ensure that a value is available. For example, req(input$abc) checks if input$abc exists. If not the App will show empty result (without returning error or break).