【问题标题】:Read and Use Several Objects in an .RData fileInput in Shiny在 Shiny 中读取和使用 .RData 文件中的多个对象输入
【发布时间】: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() .

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    此代码有效:

    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"),
        tableOutput("contents"),
        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(file, envir = .GlobalEnv)
    
        # Plot the data
        output$hist <- renderPlot({
          plot(x,y[1:100],main=z)
        })
      })
    })
    
    # Run the application 
    shinyApp(ui = ui, server = server)
    

    产生如下情节:

    【讨论】:

      猜你喜欢
      • 2016-10-30
      • 2015-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 1970-01-01
      • 2023-03-24
      相关资源
      最近更新 更多