How do I manage my R code in a shiny or shinydashboard application?

I made a shinydashboard application which now has quite a few lines of code and I'm wondering if there are ways to split the code into different ones. R files. I've seen a similar question here , but the answer doesn't help (especially it doesn't say anything about code in the back end of the application).

For the ui part, I created functions named header

, sidebar

and body

, and then just write

ui <- dashboardPage(header(), sidebar(), body())

      

It works well, and it still works if there are functions header

, sidebar

and body

must have arguments.

For the server side, I don't think a similar strategy can be applied. I am wondering if it is possible to write "local" server functions (one for each menu item) and then reunite into one central server function.

Do you think something like this is doable? More generally, thanks for your tips and ideas on how to make my code more manageable.

+3


source to share


3 answers


I'm not sure if this suits your requirement, you can create different files and do the necessary calculations in those files and save all objects (data frames or lists or literally everything) to a .Rds file using saveRDS()

in R and then upload that file to server .R using loadRDS()

which will have all your saved objects. You can find the documentation here .



Then just use those objects, calling the names as you saved them earlier. Most complex Shiny apps use a file global.R

(just a general convention, you can use any name) to do heavy computation and follow the approach above.

+2


source


You can always use source

to call other R files on the server. R:



  • Use source

    as usual in normal R outside of any reactive functions.

  • Use source("xxxxx", local=T)

    when you want to use it inside a reactive function, so the r codes you called will run every time that piece of reactive codes is activated.

+2


source


For the server side:

server.R:

library(shiny)
source('sub_server_functions.R')

function(input, output, session) {
    subServerFunction1(input, output, session)
    subServerFunction2(input, output, session)
    subServerFunction3(input, output, session) 
}

      

This worked for me, you may need to pass more variables to server functions. But the visibility of the reactive exit seems to allow it.

sub_server_functions.R:

subserverfunction1 <- function(input, output, session) {
  output$checkboxGroupInput1 <- renderUI({
    checkboxGroupInput('test1','test1',choices = c(1,2,3))
 })
}

subserverfunction2 <- function(input, output, session) {
  output$checkboxGroupInput2 <- renderUI({
    checkboxGroupInput('test2','test2',choices = c(1,2,3))
 })
}

subserverfunction3 <- function(input, output, session) {
  output$checkboxGroupInput3 <- renderUI({
    checkboxGroupInput('test3','test3',choices = c(1,2,3))
 })
}

      

+2


source







All Articles