如何绕过 R Shiny 中反应式表达式的延迟加载?

How to bypass lazy loading of reactive expressions in R Shiny?

在闪亮的应用程序中,假设我的数据非常大,以至于我只想执行一次操作。

server.R 脚本可能如下所示:

shinyServer(function(input, output, session) {
  data <- matrix(some_x, nrow=1000, ncol=5000)

  calculation <- observe({
    data <<- some_transformation(data, input$coefficient)
  })

  output$plot1 <- renderPlot({
    plot(some_other_transformation(data))
  })

  output$plot2 <- renderPlot({
    plot(some_other_transformation(data))
  })

  output$plot3 <- renderPlot({
    invisible(input$coefficient)
    plot(some_other_transformation(data))
  })
})

为什么 plot3 的反应式表达式是唯一计算的? input 变量的存在 "induce" 是否对该表达式求值?

我的主要问题是:如何在不以某种方式提及 input 变量的情况下 "induce" 地块 1 和 2 的表达?

如果您正在执行计算,那么观察器是不适合这项工作的工具,请参阅 here。如果您只想执行一次计算,那么您应该有一个操作按钮。如果您希望每次输入更改时都执行操作,那么您应该使用反应式:

shinyServer(function(input, output, session) {
  data <- matrix(some_x, nrow=1000, ncol=5000)

  trans_data <- reactive({
    some_transformation(data, input$coefficient)
  })

  output$plot1 <- renderPlot({
    plot(some_other_transformation(trans_data()))
  })

  output$plot2 <- renderPlot({
    plot(some_other_transformation(trans_data()))
  })

  output$plot3 <- renderPlot({
    invisible(input$coefficient)
    plot(some_other_transformation(trans_data()))
  })
})

反应只有运行一次,见this:

Reactive expressions are a bit smarter than regular R functions. They cache their values and know when their values have become outdated. What does this mean? The first time that you run a reactive expression, the expression will save its result in your computer’s memory. The next time you call the reactive expression, it can return this saved result without doing any computation (which will make your app faster).