Multiple File Apps

Open the files inside intro-shiny/babynames/06-multi-file

Single file apps have their benefits. If code length is minimal, then an app.R file is more than sufficient. However, content in a web app is more than likely to grow. An app using multiple files can help with code organization and readability. It can also make it easier to collaborate with others.

There are variations on how multiple file apps are set up. The number of files can vary and internally how the UI and server are constructed can be different across apps.

At the very least, your project folder will have two files:

The global.R file is optional. The advantage of including it is to provide a clear central area to call packages and set global variables.

Sourcing Files

There’s no limit to how many files you can use for your app. Use source() to read in another R file.

Debugging

When debugging a multiple file app, use browser() instead of the standard way of setting the breakpoint.

  1. Set browser() inside a reactive context.
  2. Run the app.
  3. In the example below, browser() is within an eventReactive(). Click on the ‘go’ button when the UI is available to activate the debugger.

Code leading up to browser() will execute. Objects (e.g. df_sub) will be available in the Environment pane of the IDE.

# Server

 # change reactive to an eventReactive. Delay reaction until action button is clicked
    # allow filtering of multiple states
    filtered_df <- eventReactive(input$go, {
        df_sub <- df[name %chin% input$name & state %chin% input$state]
        
        browser()
        
        print(df_sub)
    })

Because reactives are lazy and need to be called on to work, be sure that the reactive function that browser() is in is called somewhere downstream (e.g. render*()).

# Server

  filtered_df <- eventReactive(input$go, {
      df_sub <- df[name %chin% input$name & state %chin% input$state]
      
      browser()
      
      print(df_sub)
  })

  output$main_table <- renderDT({
    
    filtered_df()
    .
    .
    .
  })