R - rename object R while saving ()

I am looking for a way to save() variable under a different name on the fly in R (bear with me! I'm sure this is not a duplicate ...). Here is an example of what I would like to achieve:

 AAA = 1 BBB = 2 XXX = 3 YYY = 4 save(AAA=XXX, BBB=YYY, file="tmp.Rdat") # does NOT save a variable AAA to file with value 3 in it, which is the aim... 

Basically, I would like the save() function to take the value XXX and save it in a file under a variable called AAA . Note that this is not a matter of renaming a variable: I could, of course, rename the variable XXX before saving, for example. AAA = XXX and then save(AAA, ..., file=...) , but that of course will ruin the AAA value in the rest of the code.

The obvious way is to create temporary variables and then restore the values:

 AAA = 1 BBB = 2 XXX = 3 YYY = 4 AAAtmp = AAA; BBBtmp = BBB # record values of AAA, BBB AAA = XXX; BBB = YYY save(AAA, BBB, file="tmp.Rdat") AAA = AAAtmp; BBB = BBBtmp # restore values of AAA, BBB 

... but everyone will agree that this is pretty dirty (especially with many other variables).

This has been undermining me for a while, and I feel that the save() function cannot do what I want. Therefore, I assume that I will have to update my code and follow the path of using another save function (for example, saveRDS() ).

Thanks for the help!

+6
source share
3 answers

It turned out to be a bit more complicated than I expected. I will be interested to know what others have come up with, as well as what may be the objection to my decision.

 saveit <- function(..., file) { x <- list(...) save(list=names(x), file=file, envir=list2env(x)) } foo <- 1 saveit(bar=foo, file="hi.Rdata") 
+7
source

I found that I can create a list and assign all the objects in the environment to each element of the list using the get function, and then I can rename each element of the list.

Other methods may be to use the "assignment" function using the "get" function

 objectNames <- ls(all.names=T) res <- list() for (o in objectNames) { res[[paste(prefix,o,sep="_")]] <- get(o) } format(object.size(res), units="Gb") 
0
source

A little faster than defining a function for the job, you can create a local environment:

 local({ AAA <- XXX BBB <- YYY save(AAA, BBB, file="tmp.Rdat") }) 

Since you are working and assigning a different environment, you do not need to store temporary variables that will still be intact in the global environment:

 > AAA [1] 1 > BBB [1] 2 
0
source

All Articles