How can I load an object into a variable name that I specify from an R data file?
If you're just saving a single object, don't use an .Rdata
file, use an .RDS
file:
x <- 5saveRDS(x, "x.rds")y <- readRDS("x.rds")all.equal(x, y)
I use the following:
loadRData <- function(fileName){#loads an RData file, and returns it load(fileName) get(ls()[ls() != "fileName"])}d <- loadRData("~/blah/ricardo.RData")
You can create a new environment, load the .rda file into that environment, and retrieve the object from there. However, this does impose some restrictions: either you know what the original name for your object is, or there is only one object saved in the file.
This function returns an object loaded from a supplied .rda file. If there is more than one object in the file, an arbitrary one is returned.
load_obj <- function(f){ env <- new.env() nm <- load(f, env)[1] env[[nm]]}