如何用R语言声明全局变量,从而不需要多次运行同一段代码?作为一个非常简单的例子,我有两个使用相同精确数据的图,但我只想计算一次数据.
以下是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$distPlot1
和output$distPlot2
都执行dist <- rnorm(input$obs)
操作,这两个操作会两次重新运行相同的代码.如何使"dist"向量运行一次,并使其可用于所有renderplot函数?我try 将dist置于功能之外,例如:
library(shiny)
shinyServer(function(input, output) {
dist <- rnorm(input$obs)
output$distPlot1 <- renderPlot({
hist(dist)
})
output$distPlot2 <- renderPlot({
plot(dist)
})
})
但是我得到一个错误,说没有找到"dist"对象.这是我真实代码中的一个玩具示例,我有50行代码,我正在粘贴到多个"渲染…"作用有什么帮助吗?
哦,是的,如果你想运行这段代码,只需创建一个文件并运行以下命令:
其中"TestShining"是我的R studio项目的名称.