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
In case anyone is looking to do this with a plain source file, rather than a saved Rdata/RDS/Rda file, the solution is very similar to the one provided by @Hong Ooi
Prints:
And in the separate source file TestSourceFile.R
Again, this solution only works if there is exactly one file, if there are more, then it will just return one of them (probably the first, but that is not guaranteed).
You could also try something like:
I'm extending the answer from @ricardo to allow selection of specific variable if the
.Rdata
file contains multiple variables (as my credits are low to edit an answer). It adds some lines to read user input after listing the variables contained in the.Rdata
file.If you're just saving a single object, don't use an
.Rdata
file, use an.RDS
file:I use the following:
Rdata file with one object