Use different sources of R files in Shiny (source())

Hi, I am building a Shiny application and I will split my app.R into several .R files.

I need each .R file containing the codes to be executed according to a condition previously selected in an input.

I tried using in server section this code:

ifelse(input$in == ‘Option1’,{source(‘file1.R’)},ifelse(input$in == ‘Option2’.{source(‘file2.R’)}))

, but it didn't work.

Is there any reference I can see or any example you know of where something similar is done?

Thank you!

Hi @Lekmonm

Folder structure:

yourFolder
  app.R
  custom/
    file1.R
    file2.R

app.R

library(shiny)

source("./custom/file1.R")
source("./custom/file2.R")

# basic example
shinyApp(
  ui = fluidPage(
    selectInput("variable", "Variable:",
                c("mtcars",
                  "airquality")),
    tableOutput("data")
  ),
  server = function(input, output) {
    output$data <- renderTable({
      switch (input$variable,
              "mtcars" = myFunc1(),
              "airquality" = myFunc2()   
              )
    }, rownames = TRUE)
  }
)

custom/file1.R

myFunc1 <- function(){
  mtcars
}

custom/file2.R

myFunc2 <- function(){
  airquality
}

That would be the simplest approach to get you started. Once this gets more complex in size and functions you should think about spliting the project further into

  • ui.R
  • server.R
  • global.R (startup to source other files etc)

Once you are production ready converting into an R package is the way to go Chapter 20 Packages | Mastering Shiny .