R Shiny-在应用程序启动时创建全局数据框 [英] R Shiny - create global data frame at start of app

查看:115
本文介绍了R Shiny-在应用程序启动时创建全局数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个闪亮的应用程序,并且每次应用程序打开时我都需要重建一个解析json文件的数据框(因为json文件将更改).然后,应用程序中的功能将需要访问此数据框.将代码放在server.R的前面实际上并不会创建数据帧.另一种方法是创建一个创建数据框架的函数,并在每次需要该数据框架时调用该函数,但这将在我每次需要它时重新创建该数据框架.

I'm building a shiny app, and I need to rebuild a dataframe that parses a json file every time the app opens (since the json file will change). Then, functions in the app will need to access this data frame. Putting the code just in front of server.R does not actually create the data frame. Another way would be to create a function that creates the data frame, and call that function every time I need the data frame, but that would re-create the data frame every time I need it.

是否有一种方法可以一次创建数据帧并将其保存为变量名,以便在需要时可以由应用程序其余部分的函数访问?

Is there a way to create the data frame once, and save it in a variable name, that can be accessed by functions in the rest of the application when needed?

现在,我在server.R中的代码遵循以下结构.但是,在此永远不会调用填充myDF的for循环.另一方面,我不想将其放在每次需要myDF时都会调用的函数中,而每次都需要重新创建它.我只想在应用程序启动时创建myDF,然后将其另存为myDF,以便我可以使用它.

Right now my code in server.R follows this structure below. However, here the for loop that fills in myDF is never called. On the other hand, I don't want to put it in a function that is called every time I need myDF, recreating it every time. I'd just like to create myDF on start of app, and save it as myDF so that I can use it.

json_file <- "file.json"
json_data <- fromJSON(json_file)
myDF <- as.data.frame(ncol = ..., nrow = ...) #creates an empty data frame myDF

for (b in field_names) {
    #code that fills in myDF
}

myFunc <- function(inputs) {
    #a function that uses myDF
}

shinyServer(function(input, output, session) {

  output$out1 <-renderText({
      myFunc(input$inputs)
  })
}

推荐答案

将以下内容放入应用目录中名为global.R的文件中(与server.Rui.R相同),它将在初始化时运行一次的应用程序.

Put the following in a file called global.R in your app's directory (same as server.R and ui.R), it will run once at the initialization of the app.

json_file <- "file.json"
json_data <- fromJSON(json_file)
myDF <- as.data.frame(ncol = ..., nrow = ...) #creates an empty data frame myDF

for (b in field_names) {
    #code that fills in myDF
}

这篇关于R Shiny-在应用程序启动时创建全局数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆