2
votes

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

1 Answers

4
votes

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?