我正在开发一个闪亮的应用程序,它将读取一些RData文件并显示包含内容的表.这些文件由脚本生成,最终将数据转换为数据帧.然后使用save()函数保存它们.
在闪亮的应用程序中,我有三个文件:
ui.R,server.R和global.R
我希望在一段时间内读取文件,以便在文件更新时更新它们,因此我使用:
reactiveFileReader()
Run Code Online (Sandbox Code Playgroud)
我已经按照我在网上找到的一些说明进行了操作,但是我一直收到错误"错误:缺少需要TRUE/FALSE的值".我试图简化这个,所以我没有使用:
reactiveFileReader()
Run Code Online (Sandbox Code Playgroud)
功能,只需在server.R中加载文件(也在global.R文件中尝试过).再次,
load()
Run Code Online (Sandbox Code Playgroud)
语句正在读取数据框.通过加载文件,然后将文件分配给变量并执行"as.data.table",我有一点工作,但这应该无关紧要,这应该以数据帧格式读取就好了.我认为这是一个范围问题,但我不确定.有帮助吗?我的代码是:
非常感谢!
这篇文章的灵感源自http://www.r-bloggers.com/safe-loading-of-rdata-files/.Rdata文件被加载到一个新环境中,确保它不会产生意外的副作用(覆盖现有的变量等).单击该按钮时,将生成一个新的随机数据框,然后将其保存到文件中.然后,reactiveFileReader将文件读入新环境.最后,我们访问新环境中的第一个项目(假设Rdata文件只包含一个作为数据框的变量)并将其打印到表中.
library(shiny)
# This function, borrowed from http://www.r-bloggers.com/safe-loading-of-rdata-files/, load the Rdata into a new environment to avoid side effects
LoadToEnvironment <- function(RData, env=new.env()) {
load(RData, env)
return(env)
}
ui <- shinyUI(fluidPage(
titlePanel("Example"),
sidebarLayout(
sidebarPanel(
actionButton("generate", "Click to generate an Rdata file")
),
mainPanel(
tableOutput("table")
)
)
))
server <- shinyServer(function(input, output, session) {
# Click the button to generate a new random data frame and write to file
observeEvent(input$generate, {
sample_dataframe <- data.frame(a=runif(10), b=rnorm(10))
save(sample_dataframe, file="test.Rdata")
rm(sample_dataframe)
})
output$table <- renderTable({
# Use a reactiveFileReader to read the file on change, and load the content into a new environment
env <- reactiveFileReader(1000, session, "test.Rdata", LoadToEnvironment)
# Access the first item in the new environment, assuming that the Rdata contains only 1 item which is a data frame
env()[[names(env())[1]]]
})
})
shinyApp(ui = ui, server = server)
Run Code Online (Sandbox Code Playgroud)