R中是否存在全局变量?
如何在中使用R声明全局变量,以便不需要多次运行同一段代码?作为一个非常简单的例子,我有两个使用相同精确数据的图,但我只想计算一次数据 以下是ui.R文件:R中是否存在全局变量?,r,shiny,global-variables,R,Shiny,Global Variables,如何在中使用R声明全局变量,以便不需要多次运行同一段代码?作为一个非常简单的例子,我有两个使用相同精确数据的图,但我只想计算一次数据 以下是ui.R文件: library(shiny) # Define UI for application that plots random distributions shinyUI(pageWithSidebar( # Application title headerPanel("Hello Shiny!"), # Sidebar with a sl
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")
)
))
library(shiny)
shinyServer(function(input, output) {
output$distPlot1 <- renderPlot({
dist <- rnorm(input$obs)
hist(dist)
})
output$distPlot2 <- renderPlot({
dist <- rnorm(input$obs)
plot(dist)
})
})
以下是server.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")
)
))
library(shiny)
shinyServer(function(input, output) {
output$distPlot1 <- renderPlot({
dist <- rnorm(input$obs)
hist(dist)
})
output$distPlot2 <- renderPlot({
dist <- rnorm(input$obs)
plot(dist)
})
})
但是我得到一个错误,说没有找到“dist”对象。这是我真实代码中的一个玩具示例,我将50行代码粘贴到多个“渲染…”函数中。有什么帮助吗
哦,是的,如果您想运行此代码,只需创建一个文件并运行以下命令:
图书馆(闪亮)
getwd()
runApp(“C:/Desktop/R项目/TestShining”)
其中“testshinny”是我的R studio项目的名称。上的此页解释了shinny变量的范围
全局变量可以放入server.R
(根据里卡多的回答)或Global.R
global.R中定义的对象与shinyServer()之外的server.R中定义的对象相似,但有一个重要区别:它们对ui.R中的代码也是可见的。这是因为它们被加载到R会话的全局环境中;闪亮应用程序中的所有R代码都在全局环境或其子环境中运行
在实践中,没有多少次需要在server.R和ui.R之间共享变量。ui.R中的代码在启动闪亮应用程序时运行一次,并生成一个HTML文件,该文件被缓存并发送到每个连接的web浏览器。这可能有助于设置某些共享配置选项
正如@nico在上面列出的链接中所提到的,您也可以使用Just do
dist Yes来计算dist,但是当您有50行代码需要计算dist时,您该怎么做呢?只需将这50行代码放在reactive({…})
中,返回最后一行中的dist
的值reactive
只是一个使其内容成为reactive的包装器。更好的做法是将函数的大部分放在global中,并从reactive()调用它,这样您就可以在运行appglobal变量时测试函数,而不必停止执行reactive
。所以你不能像dist@Ramnath那样做:如果你想要全局反应变量,你可以将它们定义为。但不能input$…
。这些必须在shinyServer
中定义。谢谢!这个答案肯定救了我一天,希望我能给你更多的声誉点!
foo <- runif(10)