作者:Cherish雪蕊诗_425 | 来源:互联网 | 2023-09-14 18:52
HowdoyoudeclareglobalvariablesinwithRShinysothatyoudonotneedtorunthesamepieceso
How do you declare global variables in with R Shiny so that you do not need to run the same pieces of code multiple times? As a very simple example I have 2 plots that use the same exact data but I only want to calculate the data ONCE.
如何在R中声明全局变量,从而不需要多次运行相同的代码片段?作为一个非常简单的例子,我有两个图使用相同的数据但是我只想计算一次数据。
Here is the ui.R file:
这是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")
)
))
Here is the server.R file:
这是服务器。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)
})
})
Notice that both output$distPlot1
and output$distPlot2
do dist <- rnorm(input$obs)
which is re-running the same code twice. How do you make the "dist" vector run once and make it available to all the renderplot functions? I have tried to put the dist outside the functions like:
注意,输出$distPlot1和输出$distPlot2都dist <- rnorm(输入$obs),它们正在重新运行相同的代码两次。如何使“dist”向量运行一次并使其对所有的renderplot函数都可用?我试过把区间放在函数之外,比如:
library(shiny)
shinyServer(function(input, output) {
dist <- rnorm(input$obs)
output$distPlot1 <- renderPlot({
hist(dist)
})
output$distPlot2 <- renderPlot({
plot(dist)
})
})
But I get an error saying the "dist" object is not found. This is a toy example in my real code I have 50 lines of code that I am pasting into multiple "Render..." function. Any help?
但是我得到一个错误,说“dist”对象没有找到。这是我的真实代码中的一个玩具示例,我将50行代码粘贴到多个“呈现…”函数中。任何帮助吗?
Oh yea if you want to run this code just create a file and run this: library(shiny) getwd() runApp("C:/Desktop/R Projects/testShiny")
噢,如果你想运行这段代码,只要创建一个文件并运行它:library(闪亮的)getwd() runApp(“C:/Desktop/R Projects/ testbling”)
where "testShiny" is the name of my R studio project.
我的R studio项目的名字是“testbling”。
2 个解决方案