Loading User input .Rdata on Shiny App

有些话、适合烂在心里 提交于 2020-01-01 18:21:18

问题


I am working on a Shiny app which needs to take a .Rdata file as input from the user and perform certain operations on it before producing an output. So basically, after the user chooses a file, I need to load the data and store its contents which is expected to be an R list object in a variable for further use. I tried many ways but I just can't load the .Rdata file or store it in a variable. Could someone please help? I know this question has been asked over SO in the past but the answers were unclear. Any help will be highly appreciated.


回答1:


What if you try to use the new.env function and load the .Rdata in to a new environment.

library(shiny)
server <- function(input, output) {
  # Global variable to store loaded environment
  env <<- NULL

  load_Rdata <- function(){
    if(is.null(input$file)) return(NULL)
    inFile <- isolate({ input$file })

    # Create new environment to load data into
    n.env  <- new.env()
    env    <<- n.env
    load(inFile$datapath, envir=n.env)

    # Check if specified variable exists in environment
    if( !is.null(n.env$var) ){
      output$out <- renderPrint({ str(n.env$var) })
    }
    else{
      output$out <- renderPrint({ "No variable var in .Rdata file" })
    }
  }

  save_Rdata <- function(){
    if ( !is.null(env) ){
      env$new.var <- "My new variable"
      save(env, file="~/savedWorkspace.Rdata")
    }
    else{
      output$out <- renderPrint({ "No .Rdata file loaded" })
    }
  }

  observeEvent(input$btnLoad,{
    load_Rdata()
  })
  observeEvent(input$btnSave,{
    save_Rdata()
  })
}

ui <- shinyUI(fluidPage(
  fileInput("file", label = "Rdata"),
  actionButton(inputId="btnLoad","Load"),
  actionButton(inputId="btnSave","Save"),
  verbatimTextOutput("out")
))

shinyApp(ui = ui, server = server)

The saved variable can be accessed through:

> load("~/savedWorkspace.Rdata")
> env$new.var
[1] "My new variable"

And a example workspace to load can be created as:

> var <- "My variable to load"
> save.image(file="~/myWorkspace.Rdata") 

Was it something like this you were looking for?



来源:https://stackoverflow.com/questions/33071712/loading-user-input-rdata-on-shiny-app

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!