I found this code from J. Cheng as an example of freezeReactiveValue. However, before the plot is displayed, occasionally the error is momentarily displayed in place of the plot. (it takes a few changes of the inputs to get this.) As i understand, the problem is that for a short period of time - the X and Y (columns) are staying for the previous dataset, and don't match up to the new dataset. For example, I get error message "Error in FUN: object 'speed' not found" for a second after I select "pressure" dataset. (but only if beforehand "cars" dataset was selected with x=Speed and y=pressure.) Clearly, the plot is attempting to grab x variable before it had chance to be updated, but I don't know how to prevent this from happening. Would appreciate any tips you have!!! Thank you!
library(shiny)
library(ggplot2)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("dataset", "Dataset", c("cars", "pressure", "mtcars")),
selectInput("x", "x variable", character(0)),
selectInput("y", "y variable", character(0))
),
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
dataset <- reactive({
get(input$dataset, "package:datasets")
})
observe({
freezeReactiveValue(input, "x")
freezeReactiveValue(input, "y")
columns <- names(dataset())
updateSelectInput(session, "x", choices = columns, selected = columns[[1]])
updateSelectInput(session, "y", choices = columns, selected = columns[[2]])
})
output$plot <- renderPlot({
Sys.sleep(2)
req(input$dataset,input$x,input$y)
ggplot(dataset(), aes_string(input$x, input$y)) + geom_point()
})
}
shinyApp(ui, server)