Hello everyone,
I'm trying to build a data visualization app with Shiny. Several datasets can be loaded and each time a new dataset is loaded a selectInput is updated with the names of the variable in the dataset. Depending on the selected variable a plot is given as output.
Hereafter, a short example:
library(shiny)
ui <- fluidPage(
titlePanel(
"BEAMM - Data visualisation tool"
),
sidebarLayout(
sidebarPanel(
selectInput("dataset",
label = "Select a dataset:",
choices = c("dataset1", "dataset2")),
selectInput("var",
label = "Select a variable:",
choices = NULL),
),
mainPanel(
plotOutput("plot")
)
)
)
server <- function(input, output, session) {
inputData <- reactive({
if (input$dataset == "dataset1") {
df <- data.frame(x1 = rnorm(100),
x2 = rnorm(100))
} else if (input$dataset == "dataset2") {
df <- data.frame(y1 = rnorm(100),
y2 = rnorm(100))
}
df
})
observe({
inputData()
var_names <- colnames(inputData())
updateSelectInput(session, "var", choices = var_names, selected = var_names[1])
})
output$plot <- renderPlot({
req(input$var, cancelOutput = TRUE)
inputData() %>% ggplot(aes(x = !!sym(input$var))) + geom_density()
})
}
shinyApp(ui, server)
The problem appears when switching from "dataset1" to "dataset2". Before showing the correct plot of variable "y1", there is an error: variable "x1" is not found. My question is: how is possible to update input$var before generating the plot and avoid this error?
Thanks for your help,
Best regards,
Alessandro