【发布时间】:2017-08-24 01:59:38
【问题描述】:
我想访问和使用 Shiny App 用户上传的 .Rdata 文件中的多个对象。
可以通过在global.R 中简单调用load() 来访问存储在.Rdata 中的多个对象,但是当.Rdata 文件上传时,我不知道如何访问和使用这些对象。
模仿this related question where the .Rdata file contains only one object.的可重现示例
library(shiny)
# Define several objects and store them to disk
x <- rnorm(100)
y <- rnorm(200)
z <- "some text for the title of the plot"
save(x, file = "x.RData")
save(x, y, z, file = "xyz.RData")
rm(x, y, z)
# Define UI
ui <- shinyUI(fluidPage(
titlePanel(".RData File Upload Test"),
mainPanel(
fileInput("file", label = ""),
actionButton(inputId="plot","Plot"),
plotOutput("hist"))
)
)
# Define server logic
server <- shinyServer(function(input, output) {
observeEvent(input$plot,{
if ( is.null(input$file)) return(NULL)
inFile <- isolate({input$file })
file <- inFile$datapath
# load the file into new environment and get it from there
e = new.env()
name <- load(file, envir = e)
data <- e[[name]]
# Plot the data
output$hist <- renderPlot({
hist(data)
})
})
})
# Run the application
shinyApp(ui = ui, server = server)
这在上传x.RData 时有效,但不适用于xyz.RData,它会给出以下错误消息:
Warning: Error in [[: wrong arguments for subsetting an environment
Stack trace (innermost first):
65: observeEventHandler [/Users/.../Desktop/app.R#31]
1: runApp
理想情况下,由于 .RData 中的三个不同对象将被重用,我正在寻找一种解决方案,该解决方案将创建可在多个 renderXXX() 中重用的反应元素 x()、y()、z() .
【问题讨论】: