如何在R Shiny中声明全局变量,以便您不需要多次运行相同的代码片段?作为一个非常简单的例子,我有两个图,它们使用完全相同的数据,但我只想计算一次数据。
这是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
函数中使用?我尝试将dist
放在函数外面:
library(shiny)
shinyServer(function(input, output) {
dist <- rnorm(input$obs)
output$distPlot1 <- renderPlot({
hist(dist)
})
output$distPlot2 <- renderPlot({
plot(dist)
})
})
但是我收到了一个错误,说找不到"dist"对象。这只是我的玩具示例,在我的真实代码中,我有50行代码要粘贴到多个“Render…”函数中。需要帮助吗?
哦,如果你想运行这段代码,只需创建一个文件并运行以下命令: library(shiny) getwd() runApp("C:/Desktop/R Projects/testShiny")
其中“testShiny”是我的R studio项目的名称。
dist <- reactive(rnorm(input$obs))
。现在您可以在函数中使用dist()
。 - Ramnathreactive({...})
内部,并在最后一行返回dist
的值。reactive
只是一个包装器,使其内容具有反应性。 - Ramnath