【发布时间】:2013-12-18 11:05:43
【问题描述】:
如何在 R Shiny 中声明全局变量,从而无需多次运行相同的代码?作为一个非常简单的示例,我有 2 个使用相同精确数据的图,但我只想计算一次数据。
这是 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”向量运行一次并使其可用于所有渲染图函数?我试图将 dist 放在以下功能之外:
library(shiny)
shinyServer(function(input, output) {
dist <- rnorm(input$obs)
output$distPlot1 <- renderPlot({
hist(dist)
})
output$distPlot2 <- renderPlot({
plot(dist)
})
})
但我收到一条错误消息,提示找不到“dist”对象。这是我真实代码中的一个玩具示例,我将 50 行代码粘贴到多个“渲染...”函数中。有什么帮助吗?
哦,是的,如果你想运行这段代码,只需创建一个文件并运行它: 图书馆(闪亮) getwd() runApp("C:/Desktop/R Projects/testShiny")
其中“testShiny”是我的 R 工作室项目的名称。
【问题讨论】:
-
只要
dist <- reactive(rnorm(input$obs))。现在你可以在你的函数中使用它作为dist()。 -
是的,这行得通,但是当你有 50 行代码需要计算 dist 时你会怎么做?
-
只需将 50 行放入
reactive({...})中,最后一行返回dist的值。reactive只是一个包装器,使其内容具有反应性。 -
更好的做法是将大部分函数放在全局中并从 reactive() 调用它,这样您就可以在运行应用程序时测试您的函数而不必停止执行
标签: r shiny global-variables