Lekmonm
December 12, 2024, 6:16pm
1
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!
vedoa
December 15, 2024, 9:07am
2
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 .
system
Closed
March 15, 2025, 9:08am
3
This topic was automatically closed 90 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.