【问题标题】:How to make a local variable global in R using Shiny?如何使用 Shiny 在 R 中使局部变量成为全局变量?
【发布时间】:2018-10-20 19:12:08
【问题描述】:

这是我第一次使用 Shiny,如果这太简单了,请见谅。

我有一个名为 some_global_function() 的全局函数,只要按下名为 ok_inputactionButton 就会调用它。这将创建一个名为 algorithm_output 的局部变量。

现在,我希望能够在按下 另一个 actionButton (ok_means) 时访问该变量,但无需再次调用函数 some_global_function()

有办法吗?代码是这样的:

server <- function(input, output) {
  out_plots <- eventReactive(input$ok_input, {

    #### I call the function here and this is the variable I want
    #### to make global ########################################
    algorithm_output = some_global_function(3, 2, 1)

    do.call("grid.arrange", c(algorithm_output$indexes, nrow=3))
  })

  output$indexes <- renderPlot({
    out_plots()
  })

  out_means <- eventReactive(input$ok_means, {
    k = as.integer(input$k)

    #### I want to access the variable here ################
    matplot(algorithm_output$means[[k-1]], type = "l", lty=1)
    ########################################################

  })
  output$means <- renderPlot({
    out_means()
  })
}

【问题讨论】:

    标签: r scope shiny global-variables local-variables


    【解决方案1】:

    只需在任何子函数之外创建变量并使用&lt;&lt;- 更新其值。这个变量在每个会话中都是全局的。

    server <- function(input, output) {
    
      # init variable here
      algorithm_output <- NULL
    
      out_plots <- eventReactive(input$ok_input, {
    
        # to modify a global variable use <<- instead of <- or =
        algorithm_output <<- some_global_function(3, 2, 1)
    
        do.call("grid.arrange", c(algorithm_output$indexes, nrow=3))
      })
    
      output$indexes <- renderPlot({
        out_plots()
      })
    
      out_means <- eventReactive(input$ok_means, {
        k = as.integer(input$k)
    
        # you can get access to the updated value of your variable
        matplot(algorithm_output$means[[k-1]], type = "l", lty=1)
    
      })
      output$means <- renderPlot({
        out_means()
      })
    }
    

    【讨论】:

    • 强调使用&lt;&lt;-“更新”它的值!也就是说,第一次不要使用&lt;&lt;- 运算符来分配变量值。当变量尚不存在时,此运算符会将变量分配给全局环境。特别是在 Shiny 应用程序中,这可能会产生意想不到的后果,因为 Shiny 应用程序中的全局变量在用户之间/跨不同会话共享!!!
    • @Brunox13,感谢您的建议。那么我们应该如何分配一个全局变量呢?我用这样的东西来避免你提到的问题:if(!exists(deparse(substitute(dataGlobal)))) { dataGlobal &lt;- NULL }
    猜你喜欢
    • 2023-01-05
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    • 2015-06-25
    • 1970-01-01
    相关资源
    最近更新 更多