我想了解为什么在使用 eventReactive
而不是 reactive
以及 actionButton
来刷新页面时,我得到的行为与预期不同页。
例如,这个简单的 Shiny 仪表板的行为符合我的预期:加载后会显示绘图,我可以修改过滤器并在单击刷新按钮时刷新绘图。
# app1.R
library(shiny)
library(dplyr)
library(ggplot2)
species <- levels(iris$Species)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("species", "Select Iris Species",
choices = species, selected=species, multiple = TRUE),
actionButton("refresh", "Refresh")
),
mainPanel(plotOutput("scatterplot"))
)
)
server <- function(input, output) {
selected_data <- reactive({
input$refresh
isolate({
iris %>% filter(Species %in% input$species)
})
})
output$scatterplot <- renderPlot({
plot(selected_data())
})
}
shinyApp(ui = ui, server = server)
根据我对 actionButton
和 eventReactive
的理解,我认为我可以将 selected_data
的代码替换为
selected_data <- eventReactive( input$refresh, {
iris %>% filter(Species %in% input$species)
})
这样我就明确表示selected_data
仅依赖于input$refresh
。
但是,该应用程序的行为并不符合我的预期:加载后没有显示任何绘图,我必须明确单击“刷新”才能显示绘图。之后一切都会按预期进行。
以下是该应用程序第二个版本的完整代码:
# app2.R
library(shiny)
library(dplyr)
library(ggplot2)
species <- levels(iris$Species)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("species", "Select Iris Species",
choices = species, selected=species, multiple = TRUE),
actionButton("refresh", "Refresh")
),
mainPanel(plotOutput("scatterplot"))
)
)
server <- function(input, output) {
selected_data <- eventReactive( input$refresh, {
iris %>% filter(Species %in% input$species)
})
output$scatterplot <- renderPlot({
plot(selected_data())
})
}
shinyApp(ui = ui, server = server)
根据文档,当执行Shiny应用程序时,input$refresh
应该将值从NULL更改为0,这反过来会触发selected_data
的评估并显示情节。
您能解释一下为什么在 app1.R
中,绘图是在加载应用程序时显示的,而在 app2.R
中,您必须手动强制刷新吗?
有什么(干净的)方法可以让 app2.R
在加载应用程序时显示绘图吗?
最佳答案
eventReactive
中有一个参数 ignoreNULL
,默认情况下它设置为 TRUE
(如果您将其更改为 ) FALSE
它将触发。更多信息请引用?eventReactive
library(shiny)
library(dplyr)
library(ggplot2)
species <- levels(iris$Species)
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
selectInput("species", "Select Iris Species",
choices = species, selected=species, multiple = TRUE),
actionButton("refresh", "Refresh")
),
mainPanel(plotOutput("scatterplot"))
)
)
server <- function(input, output) {
selected_data <- eventReactive( input$refresh, {
iris %>% filter(Species %in% input$species)
},ignoreNULL = F)
output$scatterplot <- renderPlot({
plot(selected_data())
})
}
shinyApp(ui = ui, server = server)
关于r - Shiny 的应用程序 : eventReactive and reactive inconsistent behaviour with actionButton to "Refresh",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45431291/