R Shiny:“全球"server.R 中所有函数的变量 [英] R Shiny: "global" variable for all functions in server.R
问题描述
我将 global 放在引号中,因为我不希望 ui.R 可以访问它,而只能在 server.R 中的每个函数中访问它.这就是我的意思:
I put global in quotes because I don't want it to be accessible by ui.R, just accessible throughout every function in server.R. Here's what I mean:
shinyServer(function(input, output, session) {
df <- NULL
in_data <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
else df <<- read.csv(inFile$datapath, as.is=TRUE)
return(NULL)
})
output$frame <- renderTable({
df
})
})
shinyUI(pageWithSidebar(
sidebarPanel(fileInput("file1", "Upload a file:",
accept = c('.csv','text/csv','text/comma-separated-values,text/plain'),
multiple = F),),
mainPanel(tableOutput("frame"))
))
我在 ShinyServer 函数的开头定义了 df
,并尝试在 in_data()
中使用 <<-
赋值.但是 df
永远不会改变它的 NULL
赋值(所以 output$frame
中的输出仍然是 NULL
).有什么方法可以更改 ShinyServer 函数内 df
的整体值?然后我想在 server.R 中的所有函数中使用 df
作为上传的数据框,这样我只需调用一次 input$file
.
I have df
defined at the beginning of the shinyServer function, and try to change its global value in in_data()
with the <<-
assignment. But df
never changes its NULL
assignment (so the output in output$frame
is still NULL
). Is there any way to change the overall value of df
within a function in shinyServer? I want to then use df
as the uploaded data frame throughout all of my functions in server.R so that I only have to call input$file
once.
我看了this 帖子,但是当我尝试类似的东西时,却抛出了错误,指出没有找到 envir=.GlobalENV.总体目标是只调用一次 input$file
并使用存储数据的变量,而不是重复调用 in_data()
.
I looked at this post, but when I tried something similar, and error was thrown that envir=.GlobalENV wasn't found. The overall goal is to only call input$file
once and use the variable the data is stored in instead of repeatedly calling in_data()
.
非常感谢任何帮助!
推荐答案
使用反应式的想法是正确的方向;但是你没有做对.我刚刚添加了一行,它正在工作:
The idea to use reactive is the right direction; however you didn't do it quite right. I just added one line and it is working:
shinyServer(function(input, output, session) {
df <- NULL
in_data <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
else df <<- read.csv(inFile$datapath, as.is=TRUE)
return(NULL)
})
output$frame <- renderTable({
call.me = in_data() ## YOU JUST ADD THIS LINE.
df
})
})
为什么?因为反应式对象与函数非常相似,只有在您调用它时才会执行.因此,您的代码的标准"方式应该是:
Why? Because a reactive object is very similar to a function, which gets executed only when you call it. Thus the 'standard' way of your code should be:
shinyServer(function(input, output, session) {
in_data <- reactive({
inFile <- input$file1
if (is.null(inFile)) return(NULL)
else read.csv(inFile$datapath, as.is=TRUE)
})
output$frame <- renderTable({
in_data()
})
})
这篇关于R Shiny:“全球"server.R 中所有函数的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!