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

use*_*875 37 r global-variables shiny

如何使用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")
 )
))
Run Code Online (Sandbox Code Playgroud)

这是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)
  })

})
Run Code Online (Sandbox Code Playgroud)

请注意,两个output$distPlot1output$distPlot2dist <- rnorm(input$obs)它重新运行相同的代码两次.如何使"dist"向量运行一次并使其可用于所有renderplot函数?我试图将dist放在函数之外:

library(shiny)

shinyServer(function(input, output) {

  dist <- rnorm(input$obs)

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

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

})
Run Code Online (Sandbox Code Playgroud)

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

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

其中"testShiny"是我的R工作室项目的名称.

nic*_*ico 23

Shiny网页上的这个页面解释了Shiny变量的范围.

全局变量既可以输入server.R(根据里卡多的答案),也可以输入global.R.

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

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

  • @Ramnath:如果你想要全局反应变量,可以将它们定义为[`reactiveValues`](http://www.inside-r.org/packages/cran/shiny/docs/reactiveValues). (3认同)
  • 全局变量不是"反应性的".所以你不能在`global.R`中做`dist < - rnorm(input $ dist)`. (2认同)

Jim*_*ier 10

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

foo <<- runif(10)
Run Code Online (Sandbox Code Playgroud)

代替

foo <- runif(10)
Run Code Online (Sandbox Code Playgroud)

链接说"如果对象发生变化,那么更改的对象将在每个用户会话中可见.但请注意,您需要使用<< - 赋值运算符来更改bigDataSet,因为< - 运算符仅在本地分配值环境."

我用这个来改变闪亮的成功程度.与往常一样,要小心全局变量.