R Shiny中是否存在全局变量?

时间:2013-12-02 16:45:20

标签: r shiny global-variables

如何使用R Shiny声明全局变量,以便您不需要多次运行相同的代码片段?作为一个非常简单的例子,我有两个使用相同精确数据的图,但我只想计算数据ONCE。

以下是 ui.R 文件:

library(shiny)

# Define UI for application that plots random distributions 
shinyUI(pageWithSidebar(

# Application title
headerPanel("Hello Shiny!"),

# Sidebar with a slider input for number of observations
sidebarPanel(
sliderInput("obs", 
            "Number of observations:", 
            min = 1,
            max = 1000, 
            value = 500)
  ),

# Show a plot of the generated distribution
 mainPanel(
   plotOutput("distPlot1"),
  plotOutput("distPlot2")
 )
))

以下是 server.R 文件:

library(shiny)

shinyServer(function(input, output) {

  output$distPlot1 <- renderPlot({ 
    dist <- rnorm(input$obs)
    hist(dist)
  })

  output$distPlot2 <- renderPlot({ 
    dist <- rnorm(input$obs)
    plot(dist)
  })

})

请注意,output$distPlot1output$distPlot2都会dist <- rnorm(input$obs)执行两次相同代码的library(shiny) shinyServer(function(input, output) { dist <- rnorm(input$obs) output$distPlot1 <- renderPlot({ hist(dist) }) output$distPlot2 <- renderPlot({ plot(dist) }) }) 。如何使“dist”向量运行一次并使其可用于所有renderplot函数?我试图将dist放在以下函数之外:

{{1}}

但是我收到错误,说找不到“dist”对象。这是我真实代码中的一个玩具示例我有50行代码,我将其粘贴到多个“Render ...”函数中。有什么帮助吗?

哦,是的,如果你想运行这段代码,只需创建一个文件并运行它:     库(闪亮)     getwd()     runApp(“C:/ Desktop / R Projects / testShiny”)

其中“testShiny”是我的R studio项目的名称。

2 个答案:

答案 0 :(得分:21)

Shiny webpage上的这个页面解释了Shiny变量的范围。

全局变量既可以放在server.R(根据里卡多的答案),也可以放在global.R中。

  

global.R中定义的对象类似于在shinyServer()外面的server.R中定义的对象,但有一个重要区别:它们对ui.R中的代码也是可见的。这是因为它们被加载到R会话的全局环境中; Shiny应用程序中的所有R代码都在全局环境中运行或者是它的子代。

     

在实践中,没有多少时间需要在server.R和ui.R之间共享变量。 ui.R中的代码运行一次,当Shiny应用程序启动时,它会生成一个HTML文件,该文件被缓存并发送到每个连接的Web浏览器。这可能对设置一些共享配置选项很有用。

答案 1 :(得分:9)

正如@nico在上面列出的链接中所提到的,您还可以在函数内使用&lt;&lt; - 分类器,以便在函数外部访问变量。

foo <<- runif(10)

而不是

foo <- runif(10)

链接显示“如果对象发生变化,则更改的对象将在每个用户会话中可见。但请注意,您需要使用&lt;&lt; - 赋值运算符来更改bigDataSet,因为&lt; - 运算符仅在本地环境中指定值。“

我已经将它用于闪亮的不同程度的成功。与往常一样,要小心全局变量。