0

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)
mazu
  • 147
  • 6
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. The answer will still probably be `ls()`, you just need to set the correct `envir=` parameter. It all depends on where you are calling it from and which variables exactly you want to see. That's why an example would be helpful – MrFlick Feb 10 '23 at 14:39
  • @MrFlick thanks you're right, I've edited the question to include reproducible example – mazu Feb 10 '23 at 15:21

1 Answers1

0

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)
MrFlick
  • 195,160
  • 17
  • 277
  • 295