[英]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
中的output$frame
仍为NULL
)。 有没有办法在shinyServer中的函数中更改df
的整体值? 我想在server.R中的所有函数中使用df
作为上传的数据框,这样我只需要调用一次input$file
。
我查看了这篇文章,但是当我尝试类似的东西时,错误被抛出,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
})
})
为什么? 因为反应对象与函数非常相似,只有在调用它时才会执行。 因此,代码的“标准”方式应该是:
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()
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.