rtypesloadrda

R, assign content from .rda object with load()


This is very basic (and I suspect this has been asked elsewhere, although not quite here ).

I have a huge number of .rda files each with a single data frame. I would like to do calculations on each data frame and hence need loading them (load()). Had they been .RDS object I would something like:

#My data
x <- data.frame(a=1:3)
y <- data.frame(a=3:6)

#Save as RDS 
saveRDS(x, file = "x.rds")
saveRDS(y, file = "y.rds")

files <- c("x.rds", "y.rds")
data <- lapply(files, readRDS)

#Do something with the data in the list "data"

How can I do a similar thing using load since this you cannot assign the data - only the name - to a variable:

x <- data.frame(a=1:3)

> x
  a
1 1
2 2
3 3

save(x, file= "x.rda")
x <- load("x.rda")

> x
[1] "x"

Solution

  • If you are certain that all of your files only contain a single object, you could take advantage of the envir argument of load in a wrapper function like this:

    load_object <- function(file) {
      tmp <- new.env()
      load(file = file, envir = tmp)
      tmp[[ls(tmp)[1]]]
    }
    

    Usage would be as follows:

    not_x <- data.frame(xx = 1:5)
    save(not_x, file = "~/tmp/x.Rdata") 
    
    (x <- load_object("~/tmp/x.Rdata"))
    #  xx
    #1  1
    #2  2
    #3  3
    #4  4
    #5  5
    
    all.equal(not_x, x)
    #[1] TRUE