Search code examples
rshinyscoping

R shiny object scoping


I'm trying to access an object(a<-get(obj1,envir=parent.environment())) residing in the calling environment from the called environment myf and I can't get it working. Error I'm getting is Object obj1 not found. I tried parent.frame()also. Any ideas?

library(shiny)
shinyApp(
  ui = textOutput("test1"),
  server = function(input, output) {
    myf <- function(x) {
      a <- get(obj1, envir = parent.environment())
      return(paste0(x,a))
    }
    output$test1 <- renderText({
      obj1 <- "testing"
      a <- lapply(c("a","b","c"), myf)
      return(paste(unlist(a), collapse = ","))
    })
  }
)

NOTE : I do NOT want to create obj1 using obj1<<- as it creates in Global Environment and is available for all sessions


Solution

  • The correct solution is that you have three problems: First of all, you need to quote "obj1" like this

    get("obj1", envir = ...)
    

    Secondly, parent.environment() is not a function. It doesn't exist.

    Thirdly, you need to understand environment and calling frames a little bit to know how this works (it has nothing to do with Shiny). What you want to use is parent.frame(2) (being inside an lapply adds a layer)

    So to modify your original code, this is the solution:

    library(shiny)
    shinyApp(
      ui = textOutput("test1"),
      server = function(input, output) {
        myf <- function(x) {
          a <- get("obj1", envir = parent.frame(2))
          return(paste0(x,a))
        }
        output$test1 <- renderText({
          obj1 <- "testing"
          a <- lapply(c("a","b","c"), myf)
          return(paste(unlist(a), collapse = ","))
        })
      }
    )