How can I load an object into a variable name that I specify from an R data file?

Ryan C. Thompson picture Ryan C. Thompson · Apr 7, 2011 · Viewed 41.6k times · Source

When you save a variable in an R data file using save, it is saved under whatever name it had in the session that saved it. When I later go to load it from another session, it is loaded with the same name, which the loading script cannot possibly know. This name could overwrite an existing variable of the same name in the loading session. Is there a way to safely load an object from a data file into a specified variable name without risk of clobbering existing variables?

Example:

Saving session:

x = 5
save(x, file="x.Rda")

Loading session:

x = 7
load("x.Rda")
print(x) # This will print 5. Oops.

How I want it to work:

x = 7
y = load_object_from_file("x.Rda")
print(x) # should print 7
print(y) # should print 5

Answer

hadley picture hadley · Apr 7, 2011

If you're just saving a single object, don't use an .Rdata file, use an .RDS file:

x <- 5
saveRDS(x, "x.rds")
y <- readRDS("x.rds")
all.equal(x, y)