Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 
like image 534
Ryan C. Thompson Avatar asked Apr 07 '11 07:04

Ryan C. Thompson


People also ask

How do you assign variable names in R?

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(_).

What is an .RData file?

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.


2 Answers

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) 
like image 155
hadley Avatar answered Oct 06 '22 08:10

hadley


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") 
like image 37
ricardo Avatar answered Oct 06 '22 08:10

ricardo