Environments in R Shiny
Asked Answered
K

1

8

At http://shiny.rstudio.com/articles/scoping.html the rules for scoping in shiny are well explained. There are 3 environments or levels nested inside each other: objects available within a function, within a session and within all sessions. Using <- will change the object within the environment you are in and <<- will change it globally i.e. for all sessions.

What if I define a variable within the session but want to change it from within a function?

<- will just change it within the function so not readable by other functions and <<- will change it for all sessions. Is there nothing inbetween? Like "just one level up"?

Klug answered 1/5, 2014 at 14:2 Comment(3)
I think (not sure) this sentence is not well phrased and "<<-" rather means "one level up".Whitsun
Do you mean that using <<- within a function is supposed to change the variable within the function & shiny session but not gloablly i.e. for all shiny sessions? This doesn't tie in with my (little) experience. I will have a more detailed look / experiment and post the results here.Klug
<<- does not mean "global" but "non local". Read Yihui Xie's comments in this discussionWhitsun
K
8

Thanks for that reference Stephane. If an object is defined before the shinyServer() then using <<- anywhere within shinyServer() will change the value for all instances of the app. If the object is defined within shinyServer() then <<- (inside or outside a function) will only change the value for that instance of the app.

I put together a little app with a counter and instance ids to test this. Running two instances of the app and switching between them increasing the count demonstrates the effect of <<-

ui.r

    library(shiny)

shinyUI(pageWithSidebar(

  headerPanel("Testing Environments"),

  sidebarPanel(


    actionButton("increment_counter", "Increase Count")


  ),

  mainPanel(

    tabsetPanel(
      tabPanel("Print", verbatimTextOutput("text1"))


      ))

))

server.r

instance_id<-1000

shinyServer(function(input, output, session) {

  instance_id<<-instance_id+1
  this_instance<-instance_id

  counter<-0


  edit_counter<-reactive({

    if(input$increment_counter>counter){
    counter<<-counter+1
    }

    list(counter=counter)

  })



  output$text1 <- renderPrint({ 
    cat(paste("Session ID: ",Sys.getpid()," \n"))
    cat(paste("Global Instance ID: ",instance_id," \n"))
    cat(paste("This Instance ID: ",this_instance," \n"))
    cat(paste("Button Value: ",input$increment_counter," \n"))
    cat(paste("Counter Value: ",edit_counter()$counter," \n"))


  })



}) # end server function
Klug answered 2/5, 2014 at 14:9 Comment(1)
Thanks for your 'little app'. It is quite useful to see the different effects of <<- at different places.Captainship

© 2022 - 2024 — McMap. All rights reserved.