gpt4 book ai didi

R Shiny : "global" variable for all functions in server. R

转载 作者:行者123 更新时间:2023-12-02 21:14:37 26 4
gpt4 key购买 nike

我将全局放在引号中,因为我不希望它可以被 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"))
))

我有df定义在shinyServer函数的开头,并尝试更改其全局值in_data()<<-任务。但是df永远不会改变它的 NULL赋值(因此 output$frame 中的输出仍然是 NULL )。有什么办法可以改变df的整体值(value)在shinyServer 的函数中?我想然后使用df作为我在 server.R 中所有函数中上传的数据帧,这样我只需调用 input$file一次。

我查看了this帖子,但是当我尝试类似的操作时,抛出错误,找不到 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()
})
})

关于R Shiny : "global" variable for all functions in server. R,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31482434/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com