tri*_*ppy 7 r shiny reactive shiny-reactivity shinyapps
我有一个闪亮的应用程序,具有典型的侧边栏面板+主面板结构。
当用户在 selectInput #1 中选择新数据集时,selectInput #2(可用变量)和绘图都需要更新。我希望首先更新 selectInput #2,然后更新绘图。然而,似乎情节总是在第二个 selectInput 有机会更新之前继续更新。这会导致绘图尝试渲染无效绘图 - 即尝试使用 iris 数据集渲染 mtcars 变量的绘图,反之亦然。
有没有办法优先考虑 selectInput #2 的反应式更新发生在renderPlot 的反应式更新之前?
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)
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用该freezeReactiveValue()
功能,正如 Hadley Wickham在掌握闪亮时所建议的那样。
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, session) {
input_dataset <- reactive({
if(input$dataset == "mtcars") {
return(mtcars)
} else {
return(iris)
}
})
observeEvent(input$dataset, {
freezeReactiveValue(input, "variable")
updateSelectInput(session = session, inputId = "variable", choices = names(input_dataset()))
})
output$distPlot <- renderPlot({
ggplot(input_dataset(), aes(x = .data[[input$variable]])) +
geom_histogram()
})
}
# Run the application
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1718 次 |
最近记录: |