Home > Enterprise >  What is an environment where exists all objects from all files sourced when running Shiny App?
What is an environment where exists all objects from all files sourced when running Shiny App?

Time:12-27

When Shiny App starts, by default it sources e.g. all files with .R extension in R/ as well as app.R file or server.R and ui.R file. I imagine all objects from these files (functions mostly) lives in one common environment. How to get access to this environment? Let's say, I would like to list all objects in this environement in some renderPrint output. I have tried:

output$env <- renderPrint({
    names(rlang::global_env())
  })

But it doesn't work, it founds only ".Random.seed"

CodePudding user response:

According to this article:

all R code in a Shiny app is run in the global environment or a child of it

I think "or a child" is key here.

When you run a Shiny session that happens in an environment - let's call it A. All functions from R/ are stored in another environment - let's call it B. Now, both A and B are (grand)childs of the global environment, but B is also a (grand)parent of A.

A bit simplified we have something like this:

 -- Global environment
|   \-- B (where your functions live)
|       \-- A (current environment)

This is why you can access the functions from your app, but you cannot find the functions either in the global environment nor in the current environment of your app.

Example

Create a new folder for a Shiny application, and store the following function in R/whatever.R:

test_function <- function() print("TEST")

Now, in your application, do something like:

library(shiny)

ui <- fluidPage(
    
    mainPanel(
        verbatimTextOutput("objects")
    )
)

server <- function(input, output) {
    
    test_function()
    
    output$objects <- renderPrint({
        
        x <- pryr::parenvs(rlang::current_env())
        
        for (i in seq_len(length(pryr::parenvs(rlang::current_env())))) {
            
            print(x[[i]])
            print(names(x[[i]]))
            print("-----------------------------")
            
        }
    })
    
}

shinyApp(ui = ui, server = server)

This should print all environments and their content, starting from your current environment and ending with the global environment. test_function will be stored somewhere in between these environments.

To access the environment with your functions, write some logic to find that environment, and access everything there.


PS: If you want any object or function to be available in the global environment, you can create them in the file global.R. This will run once when the app is started, and should make everything available in the global environment. Read more about it here.

  • Related