How do you declare global variables in with R Shiny so that you do not need to run the same pieces of code multiple times? As a very simple example I have 2 plots that use t
This page on the Shiny webpage explains scoping of Shiny variables.
Global variables can either be put in server.R
(as per Ricardo's answer) or in global.R
.
Objects defined in global.R are similar to those defined in server.R outside shinyServer(), with one important difference: they are also visible to the code in ui.R. This is because they are loaded into the global environment of the R session; all R code in a Shiny app is run in the global environment or a child of it.
In practice, there aren’t many times where it’s necessary to share variables between server.R and ui.R. The code in ui.R is run once, when the Shiny app is started and it generates an HTML file which is cached and sent to each web browser that connects. This may be useful for setting some shared configuration options.
As mentioned in the link that @nico lists above, you can also use the <<- classifier inside your functions to make variables accessible outside of the function.
foo <<- runif(10)
instead of
foo <- runif(10)
The link says "If the objects change, then the changed objects will be visible in every user session. But note that you would need to use the <<- assignment operator to change bigDataSet, because the <- operator only assigns values in the local environment."
I have used this to varying levels of success in shiny. As always, be careful with global variables.