应用程序结构
我有一个闪亮的应用程序,具有典型的侧边栏面板+主面板结构。
-
侧边栏面板:侧边栏面板中有多个 selectInput 小部件,其中每个 selectInput 中的选择取决于
前一个 selectInput 的选择值。 (即,用户从 selectInput 1 中选择一个数据集,并从 selectInput 2 中选择一个变量,其中 selectInput #2 中可用作“选项”的变量取决于输入 1 的选择)
-
主面板:有一个基本的 ggplot2 可视化,它取决于侧边栏面板中所做的 2 个输入选择(数据集和变量)。
Problem
当用户在 selectInput #1 中选择新数据集时,selectInput #2(可用变量)和绘图都需要更新。我希望首先更新 selectInput #2,然后更新绘图。然而,似乎情节总是在第二个 selectInput 有机会更新之前继续更新。这会导致绘图尝试渲染无效绘图 - 即尝试使用 iris 数据集渲染 mtcars 变量的绘图,反之亦然。
有没有办法优先考虑 selectInput #2 的反应性更新beforerenderPlot 的反应式更新?
Notes
- 作为用户体验要求,我避免使用按钮来渲染绘图。
我需要绘图根据
选择。
- 在我的reprex中,我包含了打印语句来描述情节如何
尝试使用无效的选择组合进行更新。
library(shiny)
library(ggplot2)
library(dplyr)
# Define UI for application that draws a histogram
ui <- fluidPage(
titlePanel("Reactivity Test"),
# Sidebar with two input widgets
sidebarLayout(
sidebarPanel(
selectInput(inputId = "dataset",
label = "Input #1 - Dataset",
choices = c("mtcars", "iris")),
selectInput(inputId = "variable",
label = "Input #2 - Variable",
choices = NULL)
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("distPlot")
)
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
input_dataset <- reactive({
if (input$dataset == "mtcars") {
return(mtcars)
} else {
return(iris)
}
})
mtcars_vars <- c("mpg", "cyl", "disp")
iris_vars <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width")
available_vars <- reactive({
if (input$dataset == "mtcars") {
return(mtcars_vars)
} else {
return(iris_vars)
}
})
observe({
updateSelectInput(inputId = "variable", label = "Variable", choices = available_vars())
})
output$distPlot <- renderPlot({
req(input$dataset, input$variable)
print(input$dataset)
print(input$variable)
selected_dataset <- input_dataset()
selected_variable <- input$variable
filtered_data <- selected_dataset %>% select(selected_variable)
ggplot(filtered_data, aes(x = get(selected_variable))) +
geom_histogram()
})
}
# Run the application
shinyApp(ui = ui, server = server)