Search code examples
rvariablesshinyshiny-server

function to access list of variable names in R shiny app (equivalent of ls)


I have a very short question : how can I access the list of variables defined in a R Shiny App ? I am looking to something equivalent to the ls() function, which does not work as expected in R Shiny...

I would be very grateful if you could help.

Thanks in advance

Here a piece of code with what I would like to do:

library(shiny)

my_file1 = "monfichier.txt" 
my_file2 = "monfichier.txt" 

ui = fluidPage(
  fluidPage(
    br(),
    fluidRow(
      verbatimTextOutput('print_fichiers')
  )
  )
)   
server <- function(input, output,session){
  output$print_fichiers <- renderPrint({
    ## I would like to use ls() function 
    # to print the ''hard-coded'' filename stored 
    # in the variables that match the pattern ''file''
    all_files <- ls()[grepl("file", xx)]
    for(ifile in all_files) {
# would like to print 
# my_file1 = monfichier.txt and so on
      print(paste0("\n", ifile, "\t=\t\"", get(ifile)    , "\"\n"))
    }
  })
}
shinyApp(ui = ui, server = server)

Solution

  • When looking for variables ls() will use the current environment. Since you are calling it inside a function, you will only see variables local to that scope by default. You can explicitly ask for the global environment by using

    all_files <- ls(pattern="file", envir=globalenv())
    

    This will return all global variables with "file" in their name. No need to use grepl since ls already has a pattern= parameter.

    Another option would be to explicitly capture the environment you want to explore in a vairable

    library(shiny)
    
    my_file1 = "monfichier.txt" 
    my_file2 = "monfichier.txt" 
    shiny_env <- environment()
    
    ui = fluidPage(fluidPage(br(),fluidRow(verbatimTextOutput('print_fichiers'))))   
    
    server <- function(input, output,session){
      output$print_fichiers <- renderPrint({
        all_files <- ls(pattern="file", envir=shiny_env)
        print(shiny_env)
        for(ifile in all_files) {
          print(paste0("\n", ifile, "\t=\t\"", get(ifile)    , "\"\n"))
        }
      })
    }
    shinyApp(ui = ui, server = server)