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 the same exact data but I only want to calculate the data ONCE.
Here is the ui.R file:
library(shiny)
# Define UI for application that plots random distributions
shinyUI(pageWithSidebar(
# Application title
headerPanel("Hello Shiny!"),
# Sidebar with a slider input for number of observations
sidebarPanel(
sliderInput("obs",
"Number of observations:",
min = 1,
max = 1000,
value = 500)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot1"),
plotOutput("distPlot2")
)
))
Here is the server.R file:
library(shiny)
shinyServer(function(input, output) {
output$distPlot1 <- renderPlot({
dist <- rnorm(input$obs)
hist(dist)
})
output$distPlot2 <- renderPlot({
dist <- rnorm(input$obs)
plot(dist)
})
})
Notice that both output$distPlot1
and output$distPlot2
do dist <- rnorm(input$obs)
which is re-running the same code twice. How do you make the "dist" vector run once and make it available to all the renderplot functions? I have tried to put the dist outside the functions like:
library(shiny)
shinyServer(function(input, output) {
dist <- rnorm(input$obs)
output$distPlot1 <- renderPlot({
hist(dist)
})
output$distPlot2 <- renderPlot({
plot(dist)
})
})
But I get an error saying the "dist" object is not found. This is a toy example in my real code I have 50 lines of code that I am pasting into multiple "Render..." function. Any help?
Oh yea if you want to run this code just create a file and run this: library(shiny) getwd() runApp("C:/Desktop/R Projects/testShiny")
where "testShiny" is the name of my R studio project.
dist <- reactive(rnorm(input$obs))
. Now you can use it asdist()
in your functions. – Ramnathreactive({...})
returning the value ofdist
in the last line.reactive
is just a wrapper that makes its contents reactive. – Ramnath