When plotting to barplots in a Shiny app, the dataframes generated are only available to the first but not the second plot ("Error: Object df2 not found"). Copying and pasting the code to generate the data frames into the second renderPlot part solves the issue but is redundant and slows down the app. Is there a more elegant way to make data available acorss multiple renderPlot parts? I tried to use Shinys reactive() function but without success.
Here's a minimal example:
library(shiny)
library(ggplot2)
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel("Utility"),
sidebarLayout(
sidebarPanel(
sliderInput("var1",
"N",
min = 1,
max = 100,
value = 20)),
mainPanel(
plotOutput("barplot1"),
plotOutput("barplot2"))))
# Define server logic required to draw a barplot
server <- function(input, output) {
output$barplot1 <- renderPlot({
df <- as.data.frame(matrix(c(
"A", "1", rnorm(1, input$var1, 1),
"A", "2", rnorm(1, input$var1, 1),
"B", "1", rnorm(1, input$var1, 1),
"B", "2", rnorm(1, input$var1, 1)),
nrow = 4, ncol=3, byrow = TRUE))
df$V3 <- as.numeric(as.character(df$V3))
df2 <- as.data.frame(matrix(c(
"A", "1", rnorm(1, input$var1, df[1,3]),
"A", "2", rnorm(1, input$var1, df[1,3]),
"B", "1", rnorm(1, input$var1, df[1,3]),
"B", "2", rnorm(1, input$var1, df[1,3])),
nrow = 4, ncol=3, byrow = TRUE))
df2$V3 <- as.numeric(as.character(df$V3))
ggplot(df, aes(x=V1, y=V3, fill=V2)) +
geom_bar(stat="identity")
})
output$barplot2 <- renderPlot({
ggplot(df2, aes(x=V1, y=V3, fill=V2)) +
geom_bar(stat="identity")
})
}
# Run the application
shinyApp(ui = ui, server = server)