R Shiny:"global" server.R 中所有函数的变量
R Shiny: "global" variable for all functions in server.R
我将全局放在引号中是因为我不希望 ui.R 可以访问它,只是 server.R 中的每个函数都可以访问它。这就是我的意思:
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
一次。
我查看了 this post,但是当我尝试类似的操作时,出现了错误,提示未找到 envir=.GlobalENV。总体目标是只调用 input$file
一次并使用存储数据的变量而不是重复调用 in_data()
。
非常感谢任何帮助!
使用反应式的想法是正确的方向;但是你做得不太对。我刚刚添加了一行并且它正在工作:
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
})
})
为什么?因为反应对象与函数非常相似,只有在您调用它时才会执行。因此,您的代码的 'standard' 方式应该是:
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()
})
})
我将全局放在引号中是因为我不希望 ui.R 可以访问它,只是 server.R 中的每个函数都可以访问它。这就是我的意思:
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
一次。
我查看了 this post,但是当我尝试类似的操作时,出现了错误,提示未找到 envir=.GlobalENV。总体目标是只调用 input$file
一次并使用存储数据的变量而不是重复调用 in_data()
。
非常感谢任何帮助!
使用反应式的想法是正确的方向;但是你做得不太对。我刚刚添加了一行并且它正在工作:
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
})
})
为什么?因为反应对象与函数非常相似,只有在您调用它时才会执行。因此,您的代码的 'standard' 方式应该是:
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()
})
})