0

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" 
fred
  • 9,663
  • 3
  • 24
  • 34
  • 2
    Is `data` the path to the rda file? The `load()` command will return a vector with the names of all the objects loaded. You can use `mget()` to get a list of all those objects: `objs <- load(data); myobjs <- mget(objs)`. I would discourage you from using `attach()`. It's not a very good practice and it looks like you may have already done it a few times without properly calling `detach()` hence the warning message. – MrFlick Apr 11 '19 at 19:35

1 Answers1

3

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:

  • it will never overwrite anything in .GlobalEnv ... having learned that the hard way some times with unreproducible issues, this is huge for me
  • it encourages a list-like way of doing things, more important when most or all of the objects in the .rda file are the same "thing" (e.g., frame, list) and I plan on doing the same actions to each of them
  • if there is ever any doubt as to the source of the data, it won't clutter any of my namespace or global environment
r2evans
  • 141,215
  • 6
  • 77
  • 149