rrda

Load a .rda file and iterate over its objects


I loaded a rda file which basically its a list of dataframes. How do I iterate over is objects?

>load(data)
>attach(data)
 The following objects are masked _by_ .GlobalEnv:

GSE109597, GSE18897, GSE32575, GSE53232, GSE55205, GSE69039,
GSE83223, GSE87493, GSE98895
> R » objects()
[1] "GSE109597" "GSE18897"  "GSE32575"  "GSE53232"  "GSE55205"  "GSE69039" 
[7] "GSE83223"  "GSE87493"  "GSE98895" 

Solution

  • Two thoughts:

    1. Load explicitly into a new empty environment, then work on them there:

      e <- new.env(parent = emptyenv())
      load(filename, envir = e)
      out <- eapply(e, function(x) {
        # do something with x
      })
      
    2. From ?load, it returns a "character vector of the names of objects created, invisibly". If you capture the (invisible) vector, you should be able to do something like:

      nms <- load(data)
      for (nm in nms) {
        x <- get(nm)
        # do something with x
        # optional, save it back with assign(nm, x)
      }
      # or to capture all data into a list (similar to bullet 1 above)
      out <- lapply(lapply(nms, get), function(x) {
        # do something with x
      })
      

    I prefer the first (environment-based) solution for a few reasons: