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?
x = 5 save(x, file="x.Rda")
x = 7 load("x.Rda") print(x) # This will print 5. Oops.
x = 7 y = load_object_from_file("x.Rda") print(x) # should print 7 print(y) # should print 5
Variable Names Rules for R variables are: A variable name must start with a letter and can be a combination of letters, digits, period(.) and underscore(_).
The RData format (usually with extension . rdata or . rda) is a format designed for use with R, a system for statistical computation and related graphics, for storing a complete R workspace or selected "objects" from a workspace in a form that can be loaded back by R.
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)
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With