我正在使用拉絲直方圖在閃亮的應用程式中查詢樣本。在我的完整應用程式中,我疊加了一個新的直方圖來突出顯示所選區域并更新顯示過濾樣本屬性的 DT 資料表。
我注意到每次移動它時,依賴于畫筆的反應性都會被呼叫兩次。例如,table_data每次我刷直方圖時,下面的反應都會被呼叫兩次。
app.R
library(ggplot2)
library(shiny)
df <- data.frame(x = rnorm(1000))
base_histogram <- ggplot(df, aes(x))
geom_histogram(bins = 30)
# Define UI for application that draws a histogram
ui <- fluidPage(
column(
plotOutput("histogram", brush = brushOpts(direction = "x", id = "brush", delay=500, delayType = "debounce")),
width = 6
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$histogram <- renderPlot({
p <- base_histogram
current <- table_data()
if (nrow(current) > 0) {
p <- p geom_histogram(data = current, fill = "red", bins = 30)
}
p
})
table_data <- reactive({
print("called")
brushedPoints(df, input$brush)
})
}
# Run the application
shinyApp(ui = ui, server = server)
在這個玩具示例中,它幾乎不引人注意。但是在我的完整應用程式中,必須在 table_data 回應中完成大量計算,而這種雙重呼叫不必要地減慢了一切。
有什么方法可以構建應用程式,以便在畫筆結束時反應只執行一次?
這是一個 GIF,顯示table_data每個畫筆執行兩次。

uj5u.com熱心網友回復:
試試這個,每次刷子移動時只觸發一次。
library(ggplot2)
library(shiny)
df <- data.frame(x = rnorm(1000))
base_histogram <- ggplot(df, aes(x))
geom_histogram(bins = 30)
# Define UI for application that draws a histogram
ui <- fluidPage(
column(
plotOutput("histogram", brush = brushOpts(direction = "x", id = "brush", delay=500, delayType = "debounce")),
width = 6
)
)
# Define server logic required to draw a histogram
server <- function(input, output) {
output$histogram <- renderPlot({
p <- base_histogram
if(!is.null(table_data())) {
p <- p geom_histogram(data = table_data(), fill = "red", bins = 30)
}
p
})
table_data <- reactive({
if(is.null(input$brush)) return()
print("called")
brushedPoints(df, input$brush)
})
}
shinyApp(ui, server)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/355825.html
